does not implement methodSignatureForSelector: -- trouble ahead

刚开始写 Objetive-C 程序,有时候写了一个类时,一调用实例或是类的方法就报错,错误内容大约如下:

2011-06-19 01:14:10.175 Hello World[26080:40b] *** NSInvocation: warning: object 0x4654 of class 'Car' does not implement methodSignatureForSelector: -- trouble ahead
2011-06-19 01:14:10.178 Hello World[26080:40b] *** NSInvocation: warning: object 0x4654 of class 'Car' does not implement doesNotRecognizeSelector: -- abort

调用代码,非常简单,就是:

Car* car = [[Car alloc]init];
[car foo];

看错误仿佛是找不到 foo 方法,可是仔细检查再检查,方法也是有的,也没有打错字。

后来找到原因了,是源自于 Java 代码写多了的缘故,忘记了让自己定义的 Objective-C 类继承自 NSObject,写成了:

@interface Car
- (void) foo;
@end

@implementation Car
- (void) foo {
NSLog(@"Execute foo method");
}
@end

因为按照 Java 的习惯,只要不显示的继承某个类,那么默认是继承自 Object,而对于 Objective-C,我们虽说也有一个根类,叫做 NSObject,不过却没让你去偷懒,凡是 Objective-C 自定义的类都必须显式的继承自 NSObject,否则它好像什么也不是。所以没别忘了:

@interface Car : NSObject
- (void) foo;
@end

就这么简单,难道是为了保持与 C/C++ 的兼容,好像也不是,因为前面有 @interface 这个相当于伪指令的东西。看到 Objective-C 里的 @ 符号很快让我联想到宏汇编里的伪指令。

本文链接 https://yanbin.blog/does-not-implement-methodsignatureforselector-trouble-ahead/, 来自 隔叶黄莺 Yanbin Blog

[版权声明] Creative Commons License 本文采用 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 进行许可。

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments