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.
- What is an Objective-C category, and how does it differ from a Swift extension?
A category adds methods to an existing class, even a system class like NSString, without subclassing: @interface NSString (Shout). At load time the runtime… - What are associated objects, and when are they the right (or wrong) tool?
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.
- What are +load and +initialize, and which can Swift use?
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
- 4.1 · Message send, selectors, forwarding, isa
- 4.3 · NSObject, class clusters, copying
- 4.4 · @objc, what does not bridge, and error bridging
- 4.5 · Nullability, lightweight generics, Swift-friendly names
- 4.6 · Method swizzling, and when it is a footgun
- 4.7 · Reading Objective-C, blocks, and manual reference counting
- 4.8 · Mixed-language projects, costs, and migrating a large app
- 4.9 · How Objective-C declarations arrive in Swift
- 4.10 · The runtime up close: introspection, encodings, IMPs and exceptions
- 4.11 · Key-value coding and observing
- 4.12 · What crosses the boundary: inference and concurrency