关于防止App Crash的方法
项目Crash的原因主要有以下几种:
-
unrecognized selector crash (找不到方法)
-
NSTimer crash (定时器)
-
Container crash(数组越界,插nil等)
-
NSString crash (字符串操作的crash)
-
NSNotification crash (通知未移除)
-
KVO crash(譬如某一属性的多次侦听,或是忘记removeObserver 或是多次removeObserver导致的crash)
-
KVC crash
以上几种是常见的可以拦截的。但有一点些是不好拦截的 例如 野指针,线程的循环引用,代理的不合理引用,webView的使用不当。主要是涉及到 线程 ,内存,强弱引用方面的问题无法拦截。一般拦截的主要是各种越界,以及OC中一些方法参数不正确,无法响应等造成的闪退。
解决思路:
一般是通过Runtime来实现。通过方法拦截方法 交换方法实现。
对runtime不熟的可以先看看这篇博文:http://yulingtianxia.com/blog/2014/11/05/objective-c-runtime/
//实现拦截主要是下面的方法 通过交换IMP指针 实现方法的交换
/**
* 对象方法的交换
*
* @param anClass 哪个类
* @param method1Sel 方法1(原本的方法)
* @param method2Sel 方法2(要替换成的方法)
*/
+ (void)exchangeInstanceMethod:(Class)anClass method1Sel:(SEL)method1Sel method2Sel:(SEL)method2Sel {
Method originalMethod = class_getInstanceMethod(anClass, method1Sel);
Method swizzledMethod = class_getInstanceMethod(anClass, method2Sel);
BOOL didAddMethod =
class_addMethod(anClass,
method1Sel,
method_getImplementation(swizzledMethod),
method_getTypeEncoding(swizzledMethod));
if (didAddMethod) {
class_replaceMethod(anClass,
method2Sel,
method_getImplementation(originalMethod),
method_getTypeEncoding(originalMethod));
}
else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
}
关于拦截Crash比较好的博客:
网易大白的思想:
https://www.jianshu.com/p/02157577d4e7
https://github.com/qiyer/QYCrashProtector