Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding methods dynamically

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 ?

like image 886
nacho4d Avatar asked Jul 25 '11 05:07

nacho4d


1 Answers

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.

like image 78
Jacob Relkin Avatar answered Sep 25 '22 01:09

Jacob Relkin