在日常开发中,当程序崩溃的时候是不是特别紧张呢,明明我的代码没有问题为何就崩溃了呢?
又是因为什么原因导致的呢?该怎么去避免?
APP常见崩溃:
- 数组越界,插nil等
- 字典的构造与修改
- NSString crash (字符串操作的crash)
- unrecognized selector
- UI not on Main Thread Crash (非主线程刷UI (机制待改善))
1.数组下标的越界
简易示例代码:
- (void)testArrayOut {
NSArray *array = @[@"a", @"b", @"c"];
NSLog(@"%@", array[4]);
}
崩溃信息*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndexedSubscript:]: index 4 beyond bounds [0 .. 2]'
一般对数组的操作出现Crash的情况:
* 取值:index超出array的索引范围
* 添加:新增的object为nil或者Null
* 插入:index大于count、插入的object为nil或者Null
* 删除:index超出array的索引范围
* 替换:index超出array的索引范围、替换的object为nil或者Null
2.字典的构造与修改
简易示例代码:
- (void)testDictionCrash {
NSString *aKey = nil;
NSDictionary *dictionary = @{@"a": aKey};
NSLog(@"%@", dictionary);
}
一般对字典操作出现Crash的情况:
- NSDictionary 不支持 nil 作为 key.
- NSDictionary 不支持 nil 作为 value.
崩溃信息
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object from objects[0]'
以上预防方法:
1.替换系统方法.通过 Method Swizzling 替换成自己的方法,然后再执行方法的时候加以判断.
2.使用类别扩展一个方法自定义实现对应操作后的预防.
github传送门:https://github.com/WorkerHuan/HH_ObjectSafe1