Method Swizzling
Basically, at runtime you can swap out one implementation of a method with another.
Here is a an explanation with code.
One clever use case is for lazy loading of a shared resource: usually you would implement a sharedFoo
method by acquiring a lock, creating the foo
if needed, getting its address, releasing the lock, then returning the foo
. This ensures that the foo
is only created once, but every subsequent access wastes time with a lock that isn't needed any more.
With method swizzling, you can do the same as before, except once the foo
has been created, use swizzling to swap out the initial implementation of sharedFoo
with a second one that does no checks and simply returns the foo
that we now know has been created!
Of course, method swizzling can get you into trouble, and there may be situations where the above example is a bad idea, but hey... that's why it's a hidden feature.