预防 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中 ...
随机推荐
- IntelliJ IDEA快捷键:Ctrl+Shift+空格
The smart type code completion may be used after the new keyword,to instantiate an object of the exp ...
- java12小时制的时间转换为24小时制
Java中将12小时制的时间转换为24小时制的方式如下: import java.text.SimpleDateFormat; import java.util.Date; public class ...
- #1 // BZOJ 4361 isn
Description 给出一个长度为n的序列A(A1,A2...AN).如果序列A不是非降的,你必须从中删去一个数, 这一操作,直到A非降为止.求有多少种不同的操作方案,答案模10^9+7. 题 ...
- [转]数据类型和Json格式
作者: 阮一峰 日期: 2009年5月30日 1. 前几天,我才知道有一种简化的数据交换格式,叫做yaml. 我翻了一遍它的文档,看懂的地方不多,但是有一句话令我茅塞顿开. 它说,从结构上看,所有的数 ...
- drupal笔记
$app_root :网站根目录 安装 汉化:1将汉化包放置drupal8\sites\default\files\translations下安装:2极简版的话需要在extend(扩展)中安装Inte ...
- Java实验-课程设计报告一:个人银行账户管理系统SavingAccountManageSystem-具体文档+源码
课程设计报告一:个人银行账户管理系统 此文档及源码仅供参考 不得直接复制使用 author: [xxxxxxxxx xx xxxx] date: "2019-04-12" 作 者: ...
- 推荐一个spring cloud 学习路线,绝对合理化
最近没有时间所有没用给大家更新spring cloud 系列学习,在这先给大家奉献上我学习spring cloud 的路线 当然第一步先学习springboot然后: spring cloud eur ...
- Java初学者的30个常见问题
本文回答了30个Java入门级初学者的常见问题. 我可以用%除以一个小数吗? a += b 和 a = a + b 的效果有区别吗? 声明一个数组为什么需要花费大量时间?为什么Java库不用随机piv ...
- 浅谈CSS和JQuery实现鼠标悬浮图片放大效果
对于刚刚学习网页前台设计的同学一定对图片的处理非常苦恼,那么这里简单的讲解一下几个图片处理的实例. 以.net为平台,微软的Visual Studio 2013为开发工具,当然前台技术还是采用CSS3 ...
- request.environ.get('wsgi.websocket')
前言 websocket 是一种html5新的接口,以前服务器推送需要进行ajax等方式进行轮训,对服务器压力较高,随着新标准的推进,使用websocket在推送等方面已经是比较成熟了,并且各个浏览器 ...