Design Element
Comment on "Replacing Objective-C Methods at Runtime"
by Matt Gallagher — Mar 30
Note about this approach (often called "method swizzling") in Objective-C 2.0:

In Objective-C 2.0 (Mac OS X 10.5 Leopard and later) the approved way to do this uses the method_exchangeImplementations function instead. As in:

Method frogs = class_getInstanceMethod([MiniObject class], @selector(generateFrogs)); Method lizards = class_getInstanceMethod([Controller class], @selector(generateLizards)); method_exchangeImplementations(lizards, frogs);

This approach is safer and atomic.

For those asking about applications of this approach: it is mostly used for debugging. If you replace methods like -[NSObject dealloc] but still invoke the default from your replacement, then you can perform all kinds of memory logging/debugging, etc.
Back to "Replacing Objective-C Methods at Runtime"
Design Element

Copyright © Scott Stevenson 2004-2015