OC笔记 - 如何防止unrecognized selector sent to instance错误
防止unrecognized selector sent to instance错误
1 - 我们在开发过程中经常会遇到 unrecognized selector sent to instance 错误
2 - 代码示例:调用 Person中不存在的方法,程序不会 crash
// - Person.h
#import@interface Person : NSObject -(void)run; @end
// -Person.m
#import "Person.h" @implementation Person -(void)run{ NSLog(@"Person run......."); } // 方法签名 - (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector{ if ([self respondsToSelector:aSelector]) { return [super methodSignatureForSelector:aSelector]; } // 返回找不到的方法 return [NSMethodSignature signatureWithObjCTypes:"v@:"]; } // 找不到的方法都回来到这里 - (void)forwardInvocation:(NSInvocation *)anInvocation{ NSLog(@"找不到 %@方法",NSStringFromSelector(anInvocation.selector)); } @end
// - main.m
#import#import "Person.h" int main(int argc, const char * argv[]) { Person *p1 = [Person new]; // Person中只有 run方法 [p1 run]; // 调用不存在的方法 [p1 makeTest]; [p1 goTest]; return 0; }
日志信息