Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call a Method that I saved using class_getInstanceMethod from Objective-C?

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.

like image 638
sorin Avatar asked Aug 10 '26 12:08

sorin


1 Answers

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.

like image 172
Sherm Pendley Avatar answered Aug 13 '26 10:08

Sherm Pendley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!