4.1 · Message send, selectors, forwarding, isa

Objective-C does not call methods, it sends messages. Everything dynamic about the platform, from KVO to swizzling to target-action, is a consequence of that one design.

Mental model. A method call in Objective-C is a question asked at runtime: “does this object respond to this selector?” Swift can ask it too, but only when you opt in.

Messages and selectors

How a send is looked up, named and answered.

  1. What happens when you send a message in Objective-C, and what if nothing responds? 4.1.1 · L2
    [obj doThing:x] compiles to a call to objc_msgSend(obj, @selector(doThing:), x). The runtime reads the object’s class pointer (isa), looks the selector up in…
  2. What is a selector, how does #selector map Swift names to it, and what does the colon count mean? 4.1.2 · L2
    A selector (SEL) is the runtime’s name for a message: an interned string such as insertString:atIndex:. Its colons give the argument count, and the argument…

When the answer is “no”

Forwarding, and the runtime class that hides behind your object.

  1. What are the stages of message forwarding, and when would you use them? 4.1.3 · L5
    When a selector is not found, the runtime gives the object several chances before it throws. First, resolveInstanceMethod: may add the method dynamically (how…
  2. What is isa, and why does your object’s runtime class sometimes differ from its Swift type? 4.1.4 · L5
    Every Objective-C object starts with a pointer, isa, to its class object, which holds the method table, the superclass pointer and the instance layout. The…

More in Objective-C & interop