Using NSMethodSignature on iPhone (with Obj-C 2.0 objects)

Hi guys, I'm using the following code on my phone, where "object" is Cat, which is a subclass of Animal. The animal has the color property:

NSLog(@"Object: %@", object);
NSLog(@"Color: %@", [object color]);
NSMethodSignature *signature = [[object class] instanceMethodSignatureForSelector:@selector(color)];

NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
[invocation setTarget:object];

[invocation invoke];

Output in my console:

2009-06-28 16:17:07.766 MyApplication[57869:20b] Object: <Cat: 0xd3f370>
2009-06-28 16:17:08.146 MyApplication[57869:20b] Color: <Color: 0xd3eae0>

Then I get the following error:

*** -[Cat <null selector>]: unrecognized selector sent to instance 0xd3f370

Any clues? I use this method in other classes, but I can’t understand what I am doing wrong in this case. The color selector obviously exists, but I don’t know why it is not recognized properly.

+3
source share
1 answer

Try something like this:

NSLog(@"Object: %@", object);
NSLog(@"Color: %@", [object color]);

SEL sel = @selector(color);

NSMethodSignature *signature = [[object class] instanceMethodSignatureForSelector:sel];

NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
invocation.selector = sel;
invocation.target = object;

[invocation invoke];

You were unable to call the method NSInvocation setSelector:.

NSMethodSignature , . , NSInvocation, .

+9

Source: https://habr.com/ru/post/1711449/


All Articles