Uli's Web Site
Method Swizzling considered harmful
There's a technique in Cocoa called "method swizzling". In principle, it lets you rename a method in one class and create a new one in its place by swapping the two methods' implementations. This is very useful when you want to place a category on a system class to replace a method, but you still want to be able to call the original method.
For a long time, people have been using the Method Swizzling sample code on CocoaDev. However, that piece of code had a big problem: It replaced the method, even if it was inherited from a superclass. On the other hand, your new method (which contained the old code) was only available in your subclass. So, by swizzling, you could accidentally inject your code at too high a level. Some people tried to just add if( [self class] == [NSSuperclass class] ), but of course that was unable to find the swizzled method with the original implementation, because that was in your subclass. Ouch.
Moreover, if you were swizzling someone else's class (and that was after all the main use: To modify system classes), all it took to break your code, even if it worked, was for that other person to move a method up in the class hierarchy, which is not an uncommon occurrence during refactoring.
The solution was to check at runtime for the case where a method is inherited from the superclass and instead of swizzling it there, to add a method at runtime that simply calls through to super. Once that is done, you have a method at the right level to swizzle safely.
Looks like Kevin Ballard came up with a safe and working implementation of method swizzling. Thanks, Kevin!
Created: 2007-04-05 @956 Last change: 2007-04-05 @987 | Home | Admin | Edit|
© Copyright 2003-2021 by M. Uli Kusterer, all rights reserved.