'Calling a method' OR 'sending a message' in Objective C

前端 未结 5 1157
旧巷少年郎
旧巷少年郎 2020-12-04 09:15

In C or any ECMAscript based language you \'call a public method or function\' on an object. But in documentation for Objective C, there are no public method calls, only the

5条回答
  •  抹茶落季
    2020-12-04 10:06

    No, there's nothing at all wrong with thinking of it like that. They are called messages because they are a layer of abstraction over functions. Part of this comes from Objective C's type system. A better understanding of messages helps:

    full source on wikipedia (I've picked out some of the more relevant issues)

    Internal names of the function are rarely used directly. Generally, messages are converted to function calls defined in the Objective-C runtime library. It is not necessarily known at link time which method will be called because the class of the receiver (the object being sent the message) need not be known until runtime.

    from same article:

    The Objective-C model of object-oriented programming is based on message passing to object instances. In Objective-C one does not call a method; one sends a message. The object to which the message is directed — the receiver — is not guaranteed to respond to a message, and if it does not, it simply raises an exception. Smalltalk-style programming allows messages to go unimplemented, with the method resolved to its implementation at runtime. For example, a message may be sent to a collection of objects, to which only some will be expected to respond, without fear of producing runtime errors. (The Cocoa platform takes advantage of this, as all objects in a Cocoa application are sent the awakeFromNib: message as the application launches. Objects may respond by executing any initialization required at launch.) Message passing also does not require that an object be defined at compile time.

提交回复
热议问题