4.10 · The runtime up close: introspection, encodings, IMPs and exceptions

The Objective-C runtime is a small C API you can call from Swift. Using it to look at a class, call an implementation directly or build a class on the fly shows what message sending, KVO and mocking libraries really do.

Mental model. The runtime is a set of public tables: classes, methods, properties, type strings. Everything dynamic in Objective-C is a read or write to those tables.

Looking and calling

Listing members, reading type strings and calling an implementation without the message send.

  1. How do you inspect a class’s methods and properties at run time, and what does a Swift class show? 4.10.1 · L3
    The runtime functions class_copyMethodList, class_copyPropertyList, class_copyIvarList and class_copyProtocolList return C arrays you free afterwards, and…
  2. What is a method type encoding, and why does a wrong signature crash instead of failing to compile? 4.10.2 · L5
    The runtime does not store parameter types, it stores a type-encoding string per method: the return type, the total frame size, then each argument with its…
  3. What is an IMP, and how can you call one without sending a message? 4.10.3 · L5
    An IMP is the raw C function pointer behind a method: id (*)(id self, SEL _cmd, ...). method_getImplementation returns it and class_getMethodImplementation or…

Building and breaking

Creating classes at run time, and the exception model that Swift cannot catch.

  1. How do you create or retarget a class at run time, and why does Swift sometimes ignore it? 4.10.4 · L5
    The runtime builds classes in three steps. objc_allocateClassPair(super, name, 0) creates an unregistered subclass, class_addMethod (with a type encoding and…
  2. Why can’t Swift catch an NSException, and how do you handle one thrown by Objective-C code? 4.10.5 · L3
    Objective-C has two error systems. Recoverable failures use NSError **, which Swift imports as throws. NSException (@throw, @try/@catch) is for programmer…

More in Objective-C & interop