nacho4d
nacho4d

Reputation: 45108

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 ?

Upvotes: 5

Views: 2324

Answers (1)

Jacob Relkin
Jacob Relkin

Reputation: 163238

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.

Upvotes: 8

Related Questions