In Objective-C, does the binding of method really happen at “run-time”?

前端 未结 4 1456
忘了有多久
忘了有多久 2021-01-24 00:41

I heard that Objective-C is influenced by the \"message passing mechanism\" of SmallTalk.

Objective-C, like Smalltalk, can use dynamic typing: an object

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-24 00:58

    It has become a compiler error only within the last five years for there to be no known declaration of a method. It has to do with Automatic Reference Counting. Under ARC, the compiler is now responsible for the reference-counting-based memory management that Cocoa uses.

    Given that responsibilty, it must be able to see the declarations of methods for any messages before they are sent, so that it knows what retains and releases are appropriate.

    The method resolution (the lookup of the method on the class) does still happen at runtime, and -- particularly if you disable ARC -- you can still take advantage of message forwarding.

    One way around ARC's requirement was given by Marcelo Cantos -- cast the receiver to id. Another is to use performSelector:. A third -- though I can't recommend it -- is to use objc_msgSend() directly.

    Note that the "binding" of the method does, and always did, happen at compile time. Methods are associated with classes, when the classes are defined. Messages are distinct from methods, and it is they that resolve at runtime to a method.

提交回复
热议问题