预防 app crash 之 unrecognized selector
处理unrecognized selector异常原因
假如封装一个方法,在其他模块调用该方法时,传入参数不匹配则crash。比如下面的方法:本应该传入的参数类型为NSMutableArray,如果传入的参数类型是NSArray,导致抛出 unrecognized selector异常
|
1
2
3
|
- (void)doSomethingWithArray:(NSMutableArray *)arr{
[arr addObject:@"123"];
}
|
当然,通过 参数类型判断 也可以避免问题的发生:
|
1
2
3
4
5
6
7
|
- (void)doSomethingWithArray:(NSMutableArray *)arr{
if ([arr isKindOfClass:[NSMutableArray class]]) {
[arr addObject:@"123"];
}else{
CrashOnSimulator(@"⚠️参数类型不对哦⚠️");
}
}
|
crash提醒:
123 void CrashOnSimulator(NSString *errorMsg) {if((TARGET_OS_SIMULATOR)){raise(SIGSTOP);}}
但是,有点地方可能忘记类型判断了怎么办,有全局拦截unrecognized selector 异常的方案吗?
分析 如何全局拦截unrecognized selector 异常

oc的消息发送机制咱们都熟悉了,通过superclass指针逐级向上查找该消息所对应的方法实现,如果遇到找不的方法,还有三次补救机制。我们可以通过上面三种方法中的一种,就可以避免unrecognized selector sent to instance
第一种方法:重写 NSObject 的forwardingTargetForSelector:
⚠️filter unrecoginze seletor of intance only
思路
- 创建一个接收未知消息的类,暂且称之为
Protector - 创建一个
NSObject的分类,在分类中重写forwardingTargetForSelector: ,在这个方法中截获未实现的方法,转发给Protector。并为Protector动态的添加未实现的方法,最后返回Protector的实例对象。 - 在分类中新增一个安全的方法实现,来作为
Protector接收到的未知消息的实现
代码
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
#import "NSObject+Protector.h"
#import <objc/runtime.h>
@implementation NSObject (Protector)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation"
- (id)forwardingTargetForSelector:(SEL)aSelector{
if ([self isCurrentClassInWhiteList]) {
[[self class] warningDeveloper:aSelector];
Class protectorCls = NSClassFromString(@"ProtectorClassName");
if (!protectorCls){
protectorCls = objc_allocateClassPair([NSObject class], "ProtectorClassName", 0);
objc_registerClassPair(protectorCls);
}
if (![self isExistSelector:aSelector inClass:protectorCls]){
class_addMethod(protectorCls, aSelector, [self safeImplementation:aSelector],[NSStringFromSelector(aSelector) UTF8String]);
}
Class Protector = [protectorCls class];
id instance = [[Protector alloc] init];
return instance;
} else {
return nil;
}
}
#pragma clang diagnostic pop
- (BOOL)isCurrentClassInWhiteList{
NSArray *classNameArray = @[@"NSNull",@"NSString",@"NSArray",@"NSDictionary",@"NSURL"];
for (NSString *className in classNameArray) {
if ([self isKindOfClass:NSClassFromString(className)]) {
return YES;
}
}
return NO;
}
- (BOOL)isExistSelector: (SEL)aSelector inClass:(Class)currentClass{
BOOL isExist = NO;
unsigned int methodCount = 0;
Method *methods = class_copyMethodList(currentClass, &methodCount);
for (int i = 0; i < methodCount; i++){
Method temp = methods[i];
SEL sel = method_getName(temp);
NSString *methodName = NSStringFromSelector(sel);
if ([methodName isEqualToString: NSStringFromSelector(aSelector)]){
isExist = YES;
break;
}
}
return isExist;
}
- (IMP)safeImplementation:(SEL)aSelector{
IMP imp = imp_implementationWithBlock(^(){
NSLog(@"PROTECTOR: %@ Done", NSStringFromSelector(aSelector));
});
return imp;
}
+ (void)warningDeveloper:(SEL)aSelector{
#if DEBUG
NSString *selectorStr = NSStringFromSelector(aSelector);
NSLog(@"PROTECTOR: -[%@ %@]", [self class], selectorStr);
NSLog(@"PROTECTOR: unrecognized selector \"%@\" sent to instance: %p", selectorStr, self);
NSLog(@"PROTECTOR: call stack: %@", [NSThread callStackSymbols]);
// @throw @"方法找不到";
#endif
}
@end
|
第二种方法:重写 NSObject 的methodSignatureForSelector(有些问题,下面有个最终版)
预防 app crash 之 unrecognized selector的更多相关文章
- reason: -[UIKBBlurredKeyView candidateList]: unrecognized selector sent to instance
reason: -[UIKBBlurredKeyView candidateList]: unrecognized selector sent to instance 发现上线的app一直会有这个cr ...
- ios unrecognized selector sent to instance出现的原因和解决方案
概述:造成unrecognized selector sent to instance iphone,大部分情况下是因为对象被提前release了,在你心里不希望他release的情况下,指针还在,对 ...
- 出现“unrecognized selector sent to instance”问题原因之一及解决方法。
对于iPhone开发初学者来说,很想实现自己在iPhone上的第一个小程序,准备工作就绪侯就信心满满的开始了!一般来说大家可能都是从Hello World做起吧. 反正我是的,:),如果按照文 ...
- [NSNull intValue]: unrecognized selector sent to instance 0x375c9860
今天遇到这个问题,程序崩溃了……日志如下: -[NSNull intValue]: unrecognized selector sent to instance 0x375c9860*** Termi ...
- IOS 错误 [UIWebView cut:]: unrecognized selector sent to instance
那在什么场景中会出现这种情况呢? 如果一个包含文字的输入元素有焦点,然后按钮的点击会导致输入失去焦点,然后接下来在输入时双按会重新得到焦点并从弹出bar中选择剪切复制粘贴,就会导致此error. 也就 ...
- iOS 程序报错:reason: [NSArrayI addObject:]: unrecognized selector sent to instance
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI ad ...
- unrecognized selector sent to instance 0x10b34e810
一个错误: *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSURLEr ...
- Solve Error: 'NSInvalidArgumentException', reason: '-[UITableView mas_makeConstraints:]: unrecognized selector sent to instance 0x7fa5c402fa00'
下面是iOS开发用第三方库可能出现的错误,及其解决方法: 1. 'NSInvalidArgumentException', reason: '-[UITableView mas_makeConstra ...
- __NSArrayI removeObjectAtIndex:]: unrecognized selector sent to instance
同样是删除cell问题,帮我看看问题出现在哪,谢谢! 我的类文件myFile是继承UIViewController的(目的是为了能够在一个view里切换不同的tableView),在myFile.h中 ...
随机推荐
- java / android int类型如何判空?
/** TextUtils.isEmpty() 方法的实现 * Returns true if the string is null or 0-length. * @param str the str ...
- java.lang.RuntimeException: Unable to get provider cn.jpush.android.service.DataProvider
转自:https://blog.csdn.net/u014306335/article/details/80355169 Android Studio 3.1.2 报错: java.lang.Runt ...
- 使用.NET Core+Docker 开发微服务
.NET Core发布很久了,因为近几年主要使用java,所以还没使用过.NET Core,今天正好有一个c#写的demo,需要做成服务,不想再转成java来实现,考虑使用.NET CORE来尝下鲜, ...
- 【Java】 剑指offer(13) 剪绳子
本文参考自<剑指offer>一书,代码采用Java语言. 更多:<剑指Offer>Java实现合集 题目 给你一根长度为n绳子,请把绳子剪成m段(m.n都是整数,n> ...
- 【Java】 剑指offer(55-2) 平衡二叉树
本文参考自<剑指offer>一书,代码采用Java语言. 更多:<剑指Offer>Java实现合集 题目 输入一棵二叉树的根结点,判断该树是不是平衡二叉树.如果某二叉树 ...
- Storm消息可靠机制
一:介绍 1.介绍 默认情况是,Spout每获取一条数据,封装后发送给后面的组件,不再管后面是否处理完成或成功接收,不再考虑. 这种的情况是不用太精确,没有启用可靠性消息机制. 2.方面的体现 spo ...
- Java Swing提供的文件选择对话框 - JFileChooser
JFileChooser() 构造一个指向用户默认目录的 JFileChooser. JFileChooser(File currentDirectory) 使 ...
- bootstrap table使用总结
使用bootstrap table可以很方便的开发后台表格,对数据进行异步更新,编辑.下面就来介绍一下bootstrap table的详细使用方法: 因为之前在官网也找了很久的教程,源码感觉隐藏的比较 ...
- 安装android studio&flutter
参考:https://flutterchina.club/setup-windows/ 1.安装jdk 2.android studio下载地址 https://developer.android. ...
- 洛谷.2234.[HNOI2002]营业额统计(Splay)
题目链接 //模板吧 #include<cstdio> #include<cctype> #include<algorithm> using namespace s ...