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

前端 未结 5 1176
旧巷少年郎
旧巷少年郎 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:02

    Because of Objective-C's dynamic messaging dispatch, message sending is actually different from calling a C function or a C++ method (although eventually, a C function will be called). Messages are sent through selectors to the receiving object, which either responds to the message by invoking an IMP (a C function pointer) or by forwarding the message to its superclass. If no class in the inheritance chain responds to the message, an exception is thrown. It's also possible to intercept a message and forward it to a wholly different class (this is what NSProxy subclasses do).

    When using Objective-C, there isn't a huge difference between message sending and C++-style method calling, but there are a few practical implications of the message passing system that I know of:

    1. Since the message processing happens at runtime, instead of compile time, there's no compile-time way to know whether a class responds to any particular message. This is why you usually get compiler warnings instead of errors when you misspell a method, for instance.
    2. You can safely send any message to nil, allowing for idioms like [foo release] without worrying about checking for NULL.
    3. As @CrazyJugglerDrummer says, message dispatching allows you to send messages to a lot of objects at a time without worrying about whether they will respond to them. This allows informal protocols and sending messages to all objects in a container.
    4. I'm not 100% sure of this, but I think categories (adding methods to already-existing classes) are made possible through dynamic message dispatch.
    5. Message sending allows for message forwarding (for instance with NSProxy subclasses).
    6. Message sending allows you to do interesting low-level hacking such as method swizzling (exchanging implementations of methods at runtime).

提交回复
热议问题