1、需求:
解决崩溃报错:unrecognized selector sent to instance 0x100641940
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface Teacher : NSObject
- (void)testForwarding:(int)number;
- (void)sleep;
- (void)run;
@end
NS_ASSUME_NONNULL_END
- 只实现了一个方法
- (void)run {
NSLog(@"run--111");
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
if ([self respondsToSelector:aSelector]) {
return [super methodSignatureForSelector:aSelector];
}
return [NSMethodSignature signatureWithObjCTypes:"v@:"];
}
- (void)forwardInvocation:(NSInvocation *)anInvocation {
NSLog(@"找不到%@",NSStringFromSelector(anInvocation.selector));
}
- 调用方法
Teacher *teacher = [[Teacher alloc] init];
[teacher sleep];
[teacher testForwarding:1];
[teacher run];
打印结果:2022-01-14 09:22:33.826571+0800 block[22306:303339] 找不到sleep
2022-01-14 09:22:33.826895+0800 block[22306:303339] 找不到testForwarding:
2022-01-14 09:22:33.826932+0800 block[22306:303339] run–111
Program ended with exit code: 0
- 程序找不到另外两个没有实现的方法,也不会崩溃
2、所以通过在消息转发的这里,做一些拦截处理,可以防止某个类对象调用方法的时候,出现崩溃的情况。
3、改进方向,可以在NSObject类中实现一次,写一个Category,效果是一样的
#import "NSObject+ff.h"
@implementation NSObject (ff)
- (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