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

前端 未结 4 1454
忘了有多久
忘了有多久 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.

    0 讨论(0)
  • 2021-01-24 01:00

    Because the IDE can infer the obvious error from the context.

    When you write if (a = 1),you will get a warning. A good IDE should help you find mistakes as early as possible.

    0 讨论(0)
  • 2021-01-24 01:01

    I figured out the reason finally..

    It throw errors during compiling because -Werror flag is included, which will turn warning into error..

    http://clang.llvm.org/docs/UsersManual.html#cmdoption-Werror

    After I delete -Werror flag, everything works as expected and the error only happens at run-time.

    0 讨论(0)
  • 2021-01-24 01:04

    One job of a compiler is to catch as many errors at compile time as possible. If it can tell that the call will fail at runtime, you generally want it to complain.

    You can suppress this via casting to show that runtime resolution is happening:

    [(id)brad sayHelloTest];
    
    0 讨论(0)
提交回复
热议问题