TA的每日心情 | 汗 2024-10-15 10:05 |
---|
签到天数: 372 天 [LV.9]以坛为家II
|
对于oc开发者来讲,经常程序运行时会碰到类似"unrecognized selector sent to instance 0x7fd5bb500a30"的错误,那么这种错误是如何引起的呢,我们碰到这种错误如果去排查问题所在,我这里有碰到一种情况写出来分享一下做为参考,源代码如下:- /*
- 类方法说明
- */
- #import <Foundation/Foundation.h>
- // 创建一个Person类
- @interface Person : NSObject {
- // 为说明问题,没有定义成员变量
-
- }
- // 定义一个类方法
- + (void)printClassName;
- // 定义一个对象方法
- - (void)test;
- @end
- @implementation Person
- // 实现类方法,只输出一行字
- + (void)printClassName {
- NSLog(@"Class name is Person");
- }
- // 实现成员方法
- - (void)test {
- NSLog(@"This is a instance method!");
- }
- @end
- int main() {
- // 类直接调用类方法,这个是没有问题的
- [Person printClassName];
-
- // 创建一个对象p,这个也是没有问题
- Person *p = [Person new];
-
- // 输出对象的地址,为方便后续问题对比
- NSLog(@"%@", p);
-
- // 对象调用类方法,这句开始报错,程序被强制退出
- // 值得注意的是,如果这样调用,编译链接都是能够通过的,只会有行警告而已,报错内容在输出结果中贴出
- [p printClassName];
-
- // 类调用对象方法
- [Person test];
-
- return 0;
- }
复制代码 输出结果为:
Sian-Mac:Test yusian$ cc test.m -framework Foundation
test.m:50:8: warning: instance method '-printClassName' not found (return type defaults to 'id') [-Wobjc-method-access]
[p printClassName];
^~~~~~~~~~~~~~
test.m:7:12: note: receiver is instance of class declared here
@interface Person : NSObject {
^
test.m:53:13: warning: class method '+test' not found (return type defaults to 'id') [-Wobjc-method-access]
[Person test];
^~~~
2 warnings generated.
Sian-Mac:Test yusian$ ./a.out
2014-03-12 20:41:56.605 a.out[685:507] Class name is Person
2014-03-12 20:41:56.607 a.out[685:507] <;Person: 0x7fcceb501030> //【前两行没有问题,顺利执行!】
2014-03-12 20:41:56.607 a.out[685:507] -[Person printClassName]: unrecognized selector sent to instance 0x7fcceb501030 //【经典的报错信息来了,并且这个地址即对象地址】
2014-03-12 20:41:56.608 a.out[685:507] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Person printClassName]: unrecognized selector sent to instance 0x7fcceb501030'
*** First throw call stack:
(
0 CoreFoundation 0x00007fff9388025c __exceptionPreprocess + 172
1 libobjc.A.dylib 0x00007fff8fdc9e75 objc_exception_throw + 43
2 CoreFoundation 0x00007fff9388312d -[NSObject(NSObject) doesNotRecognizeSelector:] + 205
3 CoreFoundation 0x00007fff937de3f2 ___forwarding___ + 1010
4 CoreFoundation 0x00007fff937ddf78 _CF_forwarding_prep_0 + 120
5 a.out 0x0000000105b78ee4 main + 116
6 libdyld.dylib 0x00007fff97dca5fd start + 1
7 ??? 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
Abort trap: 6
所以,在这里对象调用了类的方法,所以系统会报这个错误,后面类调用对象方法也是类似的错误代码,但已经没机会执行了。
|
|