objective-ciphoneswizzling

Method Swizzle on iPhone device


I tried both JRSwizzle, and MethodSwizzle. They compile fine on the simulator but throw a bunch of errors when I try to compile for Device (3.x)

How do we do swizzling on the iPhone? What's the trick?


Solution

  • The CocoaDev wiki has an extensive discussion on method swizzling here. Mike Ash has a relatively simple implementation at the bottom of that page:

    #import <objc/runtime.h> 
    #import <objc/message.h>
    //....
    
    void Swizzle(Class c, SEL origSelector, SEL newSelector)
    {
        Method origMethod = class_getInstanceMethod(c, origSelector);
        Method newMethod = class_getInstanceMethod(c, newSelector);
        if(class_addMethod(c, origSelector, method_getImplementation(newMethod), method_getTypeEncoding(newMethod)))
            class_replaceMethod(c, newSelector, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));
        else
            method_exchangeImplementations(origMethod, newMethod);
    }
    

    I have not tested this, simply because I regard method swizzling as an extremely dangerous process and haven't had the need to use it yet.