Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 38 ยท Runtime and Interoperability

The Objective-C Runtime and Message Sending

See what really happens in [obj method] - objc_msgSend, selectors, the isa pointer, method lookup, dynamic resolution, forwarding, introspection and method swizzling in the Objective-C runtime.

Objective-C is C plus a small, powerful runtime library. The syntax [object doSomething] looks like a method call, but it is not a function call decided by the compiler. It is a message send, and the runtime decides at the moment it executes which code responds. That one design choice gives Objective-C its dynamism: categories, delegates, KVO, target-action, swizzling, forwarding and mock objects all grow out of it.

This lesson walks through the machinery: selectors, the isa pointer, method lookup, what happens when lookup fails, introspection, and swizzling.

What [obj foo:bar] compiles to

OBJECTIVEC
[receiver doSomethingWith:arg];
// is compiled to roughly:
objc_msgSend(receiver, @selector(doSomethingWith:), arg);

objc_msgSend takes the receiver, a selector (the method's name, interned as a SEL), and the arguments. It finds the right function (an IMP) and jumps to it. Every method receives two hidden arguments: self and _cmd (the selector being executed).

A message to nil returns zero (or nil, NO, 0.0) and does nothing. That is why [nil description] is safe, and why Objective-C code rarely needs null checks before calling.

Objects, classes and isa

An object is a struct whose first field is isa, a pointer to its class. A class is itself an object, with its own isa pointing to a metaclass (which holds class methods). A class has:

  • a name and a pointer to its superclass,
  • a method list (selector to IMP),
  • a method cache for fast repeat lookups,
  • lists of ivars, properties and protocols.
flowchart LR
  O["instance: isa, ivars"] --> C["Class Dog: methods, cache"]
  C -- "superclass" --> A["Class Animal: methods"]
  A -- "superclass" --> N["Class NSObject"]
  C --> M["Metaclass Dog: class methods"]

Lookup starts in the receiver's class and walks up the superclass chain until the selector is found.

The lookup steps

  1. Check the class's cache. If the selector is there, jump straight to the IMP.
  2. Search the class's method list, then each superclass's list, caching the hit.
  3. If nothing is found, the runtime gives you chances to handle it:
    • +resolveInstanceMethod: lets you add the method dynamically with class_addMethod.
    • -forwardingTargetForSelector: redirects the message to another object (fast forwarding).
    • -forwardInvocation: receives an NSInvocation for full flexibility.
  4. If still unhandled, doesNotRecognizeSelector: raises "unrecognized selector sent to instance".

Message dispatch as a table

The stand-in below implements this lookup: classes with a method table and a superclass pointer, a send function that walks the chain, a cache, and a fallback to "forwarding". It is the real algorithm in miniature.

C Stand-in: method lookup through the superclass chain

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Because the method list is data, a program can change it while running. That is exactly what categories (adding entries) and swizzling (swapping them) do.

Selectors and dynamic calls

OBJECTIVEC
SEL sel = @selector(setName:);
SEL byName = NSSelectorFromString(@"setName:");         // from a runtime string
if ([person respondsToSelector:sel]) {
    [person performSelector:sel withObject:@"Ada"];       // dynamic invocation
}
NSLog(@"%@", NSStringFromSelector(sel));                  // "setName:"

performSelector: returns an object and takes at most two object arguments, and ARC warns because it cannot know ownership of the result. For anything more, use NSInvocation or cast objc_msgSend to the right function type.

Introspection

Because everything is data, objects can describe themselves:

OBJECTIVEC
[obj class];                                  // its class
[obj isKindOfClass:[NSString class]];         // instance of NSString or a subclass?
[obj isMemberOfClass:[NSString class]];       // exactly NSString?
[obj respondsToSelector:@selector(count)];    // can it handle this message?
[Dog superclass];                             // Animal
NSStringFromClass([obj class]);               // class name as a string
Class c = NSClassFromString(@"Dog");          // class from a name

This is how frameworks discover your classes and call methods they did not know existed at compile time.

Querying the runtime directly

The C API in <objc/runtime.h> lets you enumerate and modify classes:

OBJECTIVEC
#import <objc/runtime.h>

unsigned int count;
Method *methods = class_copyMethodList([Dog class], &count);
for (unsigned i = 0; i < count; i++) {
    NSLog(@"%@", NSStringFromSelector(method_getName(methods[i])));
}
free(methods);

objc_property_t *props = class_copyPropertyList([Dog class], &count);   // properties
Class dynamic = objc_allocateClassPair([NSObject class], "Generated", 0); // create a class at runtime

Dynamic method resolution and forwarding

OBJECTIVEC
void dynamicImpl(id self, SEL _cmd) { NSLog(@"added at runtime: %@", NSStringFromSelector(_cmd)); }

+ (BOOL)resolveInstanceMethod:(SEL)sel {
    if (sel == @selector(magic)) {
        class_addMethod(self, sel, (IMP)dynamicImpl, "v@:");   // void, id, SEL
        return YES;
    }
    return [super resolveInstanceMethod:sel];
}

- (id)forwardingTargetForSelector:(SEL)sel {
    return self.helper;      // let another object handle messages we do not
}

@dynamic properties on Core Data models rely on this: the accessors are generated when first called. Forwarding is also how proxies (NSProxy) and mock frameworks wrap other objects.

Method swizzling

Because a class's method table maps selector to IMP, you can swap two entries:

OBJECTIVEC
+ (void)load {
    Method original = class_getInstanceMethod(self, @selector(viewDidAppear:));
    Method replacement = class_getInstanceMethod(self, @selector(my_viewDidAppear:));
    method_exchangeImplementations(original, replacement);
}

- (void)my_viewDidAppear:(BOOL)animated {
    [self my_viewDidAppear:animated];       // calls the ORIGINAL (names are swapped!)
    NSLog(@"logged: %@ appeared", self);
}

Analytics and testing tools use this to observe calls without editing the original code. It is also fragile: it is global, order-dependent, and can break when the framework changes. Use it only when no supported hook exists, do it once (in +load with dispatch_once), and prefix names.

Swapping in the table model is easy to demonstrate:

C Stand-in: swizzling by swapping table entries

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

In the real swizzled method, the replacement calls its own selector, which now points at the original, so you do not recurse. The stand-in calls original() directly to keep the picture simple.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does [receiver foo] compile to?

    Method calls are message sends resolved at runtime.
  2. 2. What happens when you send a message to nil?

    Messages to nil are no-ops that return zero-like values.
  3. 3. In what order does the runtime try to handle an unknown selector?

    resolveInstanceMethod:, forwardingTargetForSelector:/forwardInvocation:, then doesNotRecognizeSelector:.
  4. 4. What does method_exchangeImplementations do?

    It exchanges the implementations that two selectors point to.
  5. 5. What is the difference between isKindOfClass: and isMemberOfClass:?

    Kind means the class or any subclass; member means exactly that class.

Summary

  • Method calls are messages resolved at runtime by objc_msgSend using the receiver's isa and method tables.
  • Unknown selectors can be resolved, forwarded or raise an error; nil receivers ignore messages.
  • Introspection (respondsToSelector:, isKindOfClass:, <objc/runtime.h>) lets code inspect and change classes.
  • Swizzling swaps implementations; use it sparingly.

Next: Key-Value Coding and Observing