I am trying this method found in Obj-c runtime reference
BOOL class_addMethod(Class cls, SEL name, IMP imp, const char *types)
I want to add a new method like:
- [AClass drawWithFrame:(NSRect)rect inView:(id)view]
So far I have written a C function:
void drawWithFrameInView(id this, SEL this_cmd, NSRect frame, id view){
...
}
now I am ready to do:
BOOL success = class_addMethod(NSClassFromString(@"AClass"),
@selector(drawWithFrame:inView:),
(IMP)drawWithFrameInView,
"v@:@:@:");
but success
is never YES, I have tried the same approach with methods with simpler signatures and it worked. So I think the problem is last parameter: "v@:@:@:"
What should I pass in this case to get my new method working ?
This will work:
char *types = [[NSString stringWithFormat:@"v@:%s@", @encode(NSRect)] UTF8String];
BOOL success = class_addMethod(NSClassFromString(@"MyClass"),
@selector(drawWithFrame:inView:),
(IMP)drawWithFrameInView,
types);
The reason why your code doesn't work is because NSRect
is not an object, it is a typedef
to a struct
.
Learn more about type encodings here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With