3

How do I call a method that I previously saved using the code below:

SEL sel = @selector(someMethod:param:);
Method myMethod = class_getInstanceMethod([SomeClass class], sel);

As you may imagine, calling [SomeClass someMethod] is not going to work because, later, I swizzle the original method.

sorin
  • 161,544
  • 178
  • 535
  • 806
  • 1
    Why would you want to do this exactly this way? You can create `NSInvocation` or just do the `performSelector:withObject:withObject`? – Eimantas Jun 20 '11 at 14:08
  • `performSelector:` will call the new method, not the old one. Trust me, I already tried this. – sorin Jun 20 '11 at 14:15
  • 2
    Why are you swizzling? Note that swizzling methods from system frameworks is a great way to produce an app that crashes often. – bbum Jun 20 '11 at 15:38
  • What are you really trying to do? The normal way of changing the implementation of a method would be to subclass. Why can't you do this? – JeremyP Jun 20 '11 at 15:44

1 Answers1

2

You need to typecast the pointer to the proper function type, keeping in mind that methods have two implicit arguments, self and _cmd. From Apple's runtime docs:

void (*setter)(id, SEL, BOOL);

int i;

setter = (void (*)(id, SEL, BOOL))[target methodForSelector:@selector(setFilled:)];

for ( i = 0; i < 1000, i++ )
    setter(targetList[i], @selector(setFilled:), YES);

(Edit)

Keep in mind that the Method type is a struct, and in the ObjC2 runtime, it's opaque, so you don't have direct access to its members - you'll need to use method_getImplementation(myMethod) to get an IMP that you can typecast like above.

Sherm Pendley
  • 13,556
  • 3
  • 45
  • 57