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.

  1. How does method swizzling work, and why does it need dynamic in Swift? 4.6.1 · L3
    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.

  1. Why is method swizzling considered a footgun, and what do you do instead? 4.6.2 · L5
    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