4.2 · Categories, associated objects, load and initialize

Objective-C lets you add behaviour, and even storage, to a class you do not own. Swift extensions do the first half more safely, and the second half has no direct equivalent.

Mental model. A category is patching the class’s method table at load time. That is powerful, and it is also why name clashes and missing linker flags are the classic category bugs.

Extending classes you do not own

Categories against Swift extensions, and attaching storage.

  1. What is an Objective-C category, and how does it differ from a Swift extension? 4.2.1 · L2
    A category adds methods to an existing class, even a system class like NSString, without subclassing: @interface NSString (Shout). At load time the runtime…
  2. What are associated objects, and when are they the right (or wrong) tool? 4.2.2 · L3
    Since a category cannot add a stored property, the runtime offers associated objects: objc_setAssociatedObject(obj, key, value, policy) and…

Load-time hooks

The two class methods that run code for you, and when.

  1. What are +load and +initialize, and which can Swift use? 4.2.3 · L5
    Both are class methods the runtime calls for you, at different times. +load runs once per class and per category as the binary’s image is loaded, before main…

More in Objective-C & interop