25

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)

Has anyone had any luck swizzling on the iphone? Whats the trick?

TIA

dizy
  • 7,951
  • 10
  • 53
  • 54

1 Answers1

55

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 orig, SEL new)
{
    Method origMethod = class_getInstanceMethod(c, orig);
    Method newMethod = class_getInstanceMethod(c, new);
    if(class_addMethod(c, orig, method_getImplementation(newMethod), method_getTypeEncoding(newMethod)))
        class_replaceMethod(c, new, 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.

Brad Larson
  • 170,088
  • 45
  • 397
  • 571
  • 3
    thanks that worked. They key with using this was to #import #import – dizy Oct 28 '09 at 19:04
  • @funkybro - Thanks for pointing it out. I dug out an archived version of the page, before it was taken down. When the wiki comes back up, I'll replace the archive link. – Brad Larson Sep 18 '13 at 16:49
  • +1 for * swizzling as an extremely dangerous process and haven't had the need to use it yet.* – Jakub Jan 09 '14 at 12:51
  • 3
    Swizzling is super useful when building mock frameworks for unit testing. – odyth Feb 10 '14 at 00:25
  • +1 for @odyth for saying it's useful for unit testing. I'm combining method swizzling with OCMock to do unit validation on NSURLConnection request to server and response from server. Swizzling allows us an easy way to do this type of validation. – LyricalPanda Apr 08 '14 at 21:21