Cra*_*tis 3 iphone cocoa properties dynamic objective-c
嘿伙计们,我在手机上运行以下代码,其中'object'是Cat,它是Animal的子类.动物有属性'颜色':
NSLog(@"Object: %@", object);
NSLog(@"Color: %@", [object color]);
NSMethodSignature *signature = [[object class] instanceMethodSignatureForSelector:@selector(color)];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
[invocation setTarget:object];
[invocation invoke];
Run Code Online (Sandbox Code Playgroud)
我的控制台中的输出是:
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>
Run Code Online (Sandbox Code Playgroud)
然后,我收到以下错误:
*** -[Cat <null selector>]: unrecognized selector sent to instance 0xd3f370
Run Code Online (Sandbox Code Playgroud)
有线索吗?我在其他类中使用这种类似的方法,但我无法弄清楚在这种情况下我做错了什么.选择器'颜色'显然存在,但我不知道它为什么没有被正确识别.
尝试这样的事情:
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];
Run Code Online (Sandbox Code Playgroud)
你缺少一个呼叫NSInvocation的setSelector:方法.
NSMethodSignature记录方法的参数和返回值的类型信息,但不包含选择器本身.因此,如果您想要使用它,NSInvocation您还需要设置调用的选择器.
| 归档时间: |
|
| 查看次数: |
5698 次 |
| 最近记录: |