2009-06-28 34 views
3

嗨,我跑我的电话,其中“对象”是一只猫,这是动物的子类在下面的代码。动物有一个属性 '颜色':使用NSMethodSignature在iPhone(所有与obj-C 2.0属性)

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

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

[invocation invoke]; 

在我的控制台输出为:

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> 

然后,我得到以下错误:

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

任何线索?我在其他类中使用了这种类似的方法,但我无法弄清楚在这种情况下我做错了什么。选择器'颜色'显然存在,但我不知道为什么它没有被正确识别。

+2

“动物有一个属性‘颜色’......”我非常希望看到你这个属性在墨鱼子类的实现。 :-) – 2009-06-29 02:27:26

+1

幸运的是,Obj-C是一种反思语言。 :D – 2009-07-02 18:02:14

回答

9

尝试这样:

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]; 

你失踪到NSInvocationsetSelector:方法的调用。

NSMethodSignature记录键入一个方法的参数和返回值的信息,但不包含选择器本身。所以如果你想用NSInvocation来使用它,你也需要设置调用的选择器。