Sian 发表于 2014-3-12 20:49:36

unrecognized selector sent to instance 0x

       对于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() {

    // 类直接调用类方法,这个是没有问题的
    ;
   
    // 创建一个对象p,这个也是没有问题
    Person *p = ;
   
    // 输出对象的地址,为方便后续问题对比
    NSLog(@"%@", p);
   
    // 对象调用类方法,这句开始报错,程序被强制退出
    // 值得注意的是,如果这样调用,编译链接都是能够通过的,只会有行警告而已,报错内容在输出结果中贴出
    ;
   
    // 类调用对象方法
    ;
   
    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]
    ;
       ^~~~~~~~~~~~~~
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]
    ;
            ^~~~
2 warnings generated.
Sian-Mac:Test yusian$ ./a.out
2014-03-12 20:41:56.605 a.out Class name is Person
2014-03-12 20:41:56.607 a.out <;Person: 0x7fcceb501030>   //【前两行没有问题,顺利执行!】
2014-03-12 20:41:56.607 a.out -: unrecognized selector sent to instance 0x7fcceb501030    //【经典的报错信息来了,并且这个地址即对象地址】
2014-03-12 20:41:56.608 a.out *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-: 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 - + 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

所以,在这里对象调用了类的方法,所以系统会报这个错误,后面类调用对象方法也是类似的错误代码,但已经没机会执行了。



页: [1]
查看完整版本: unrecognized selector sent to instance 0x