4.6 · Method swizzling, and when it is a footgun
Swapping one method’s implementation for another at runtime is the sharpest tool in the Objective-C box. Knowing how it works also explains why it is so often the wrong one.
Mental model. Swizzling edits one shared table for the whole process. Everything that calls that selector, yours or Apple’s, now runs your code.
How it works
Exchanging implementations, and when Swift code sees the change.
- How does method swizzling work, and why does it need dynamic in Swift?
A class’s method table maps selectors to implementations (IMP function pointers). Swizzling exchanges two entries with method_exchangeImplementations (or…
Why it bites
The failure modes, and what to do instead.
- Why is method swizzling considered a footgun, and what do you do instead?
Swizzling changes behaviour process-wide and invisibly. Every caller of the selector, including system frameworks you do not control, now runs your code. It…
More in Objective-C & interop
- 4.1 · Message send, selectors, forwarding, isa
- 4.2 · Categories, associated objects, load and initialize
- 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.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