gpt4 book ai didi

objective-c - 在 iPhone 上使用 NSMethodSignature(具有 Obj-C 2.0 属性)

转载 作者:搜寻专家 更新时间:2023-10-30 19:55:58 25 4
gpt4 key购买 nike

我在手机上运行以下代码,其中“对象”是猫,它是动物的子类。动物有一个属性“颜色”:

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

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

最佳答案

尝试这样的事情:

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 一起使用,您还需要设置调用的选择器。

关于objective-c - 在 iPhone 上使用 NSMethodSignature(具有 Obj-C 2.0 属性),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1055666/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com