Sobes.tech
Junior — Middle

What method dispatch mechanism is implemented in Objective-C?

sobes.tech AI

Answer from AI

Objective-C uses a message dispatching mechanism for dynamic method invocation. Instead of calling a method directly, as in statically typed languages, an object receives a message (selector), and at runtime, the corresponding method implementation is looked up.

It works as follows:

  • When a method is called, the compiler converts the call into sending a message to an object with a specific selector.
  • At runtime, the object searches its method table for a method matching the selector.
  • If the method is found, it is invoked; if not, a method for handling missing selectors (e.g., forwardInvocation:) is called.

This approach allows for dynamic behavior, such as intercepting calls, dynamically adding methods, and other metaprogramming techniques.

Example of sending a message:

[obj performSelector:@selector(methodName)];

Or a regular call:

[obj methodName];

which is compiled into a message send.