views:

1359

answers:

3

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

+1  A: 

I have managed to swizzle some methods just by using the default objc functions for it.

IMP original = class_replaceMethod([SomeClass class], @selector(selector:), (IMP)function, "v@:");
class_addMethod([SomeClass class], @selector(anotherMethod:), original, "v@:");

This works flawlessly, both for the Simulator as the Device. You may want to take a look at the ObjCRuntime documentation for all other methods available.

If this does not work for you, please give us the errors you currently have.

JoostK
Im not sure what the (IMP)function should be
dizy
Just the name of a function. `void function(id self, SEL _cmd, id arg);` is enough to make it work. IMP is just a cast so we won't get a compiler warning.
JoostK
+4  A: 

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
thanks that worked. They key with using this was to #import <objc/runtime.h>#import <objc/message.h>
dizy
A: 

Googling around a little bit I found a Version that

  • works for Objective C 2 as well as earlier versions,
  • allows swizzling class methods as well and
  • all in all seems to be real code (from a working project) instead of just a snipplet.

Find it at the safariblock project on google code.

Holger