iOS中如何防止程序crash

1.程序中常見的crash種類有

  • 1.unSelector 方法未找到
  • 2.KVO未移除,多次添加,多次移除問題
  • 3.數(shù)組越界
  • 4.字典賦值key或value為nil
  • 5.NSString substringFromIndex 越界問題
  • 6.NSAttributedString initWithString stirng=nil問題
  • 7.通知deallooc時(shí)為移除問題

2.解決方案

1.unSelector可以利用消息轉(zhuǎn)發(fā)來解決

消息轉(zhuǎn)發(fā)有三種時(shí)機(jī)

  • 1.在resolveInstanceMethod方法里,添加方法,但是此種方式損害了原有類的結(jié)構(gòu)
+(BOOL)resolveInstanceMethod:(SEL)sel
{
    return YES;
}
  • 2.在下面方法里放回一個(gè)自定義對(duì)象,同時(shí)給此對(duì)象添加未實(shí)現(xiàn)的方法
-(id)forwardingTargetForSelector:(SEL)aSelector
{
    rerurn obj;
}

3.完整轉(zhuǎn)發(fā),對(duì)方法進(jìn)行簽名,自定義對(duì)象然后invoke

  • 這里采用第3種方式,生成方法簽名,然后forwardInvocation,這里self invoke,因?yàn)閟elf沒有此方法會(huì)捕獲到異常,避免程序崩潰
[self safe_exchangeInstanceMethod:[self class] originalSel:@selector(methodSignatureForSelector:) newSel:@selector(safe_methodSignatureForSelector:)];        
[self safe_exchangeInstanceMethod:[self class] originalSel:@selector(forwardInvocation:) newSel:@selector(safe_forwardInvocation:)];
- (NSMethodSignature *)safe_methodSignatureForSelector:(SEL)aSelector
{
    NSMethodSignature *ms = [self safe_methodSignatureForSelector:aSelector];
    if ([self respondsToSelector:aSelector] || ms){
        return ms;
    }
    else{
        return [LSSafeProxy instanceMethodSignatureForSelector:@selector(safe_crashLog)];
    }
}

- (void)safe_forwardInvocation:(NSInvocation *)anInvocation{
    @try {
        [self safe_forwardInvocation:anInvocation];
        
    } @catch (NSException *exception) {
        LSSafeProtectionCrashLog(exception,LSSafeProtectorCrashTypeSelector);
    } @finally {
    }
}
2.KVO未移除,多次添加,多次移除,observeValueForKeyPath:ofObject:change:context:未實(shí)現(xiàn)
  • 1.這里交換NSObject以下方法
[self safe_exchangeInstanceMethod:[self class] originalSel:@selector(addObserver:forKeyPath:options:context:) newSel:@selector(safe_addObserver:forKeyPath:options:context:)];
[self safe_exchangeClassMethod:[self class] originalSel:@selector(observeValueForKeyPath:ofObject:change:context:) newSel:@selector(safe_observeValueForKeyPath:ofObject:change:context:)];
[self safe_exchangeInstanceMethod:[self class] originalSel:@selector(removeObserver:forKeyPath:) newSel:@selector(safe_removeObserver:forKeyPath:)];
[self safe_exchangeInstanceMethod:[self class] originalSel:@selector(removeObserver:forKeyPath:context:) newSel:@selector(safe_removeObserver:forKeyPath:context:)];

用safe_downObservedKeyPathArray記錄有哪些人監(jiān)聽了自己,用safe_upObservedArray記錄自己監(jiān)聽了哪些對(duì)象,用來在addObserver時(shí)判斷是否添加過了,removeObserver時(shí)是否已經(jīng)移除過了,或者壓根沒有添加過不能移除,在dealloc時(shí)自動(dòng)移除,交換observeValueForKeyPath:ofObject:change:context方法避免監(jiān)聽者未實(shí)現(xiàn)此方法

3.數(shù)組越界 ,交換數(shù)組的一些方法,需要注意的就是數(shù)組有類簇,所以需要交換多個(gè)類,根據(jù)以下規(guī)則交換方法即可
// < = iOS 8:下都是__NSArrayI
//iOS9 @[] 是__NSArray0  @[@"fd"]是__NSArrayI
//iOS10以后(含10): 分 __NSArrayI、  __NSArray0、__NSSingleObjectArrayI


//__NSArrayM   NSMutableArray創(chuàng)建的都為__NSArrayM
//__NSArray0   除__NSArrayM 0個(gè)元素都為__NSArray0
// __NSSingleObjectArrayI @[@"fds"]只有此形式創(chuàng)建而且僅一個(gè)元素為__NSSingleObjectArrayI
//__NSArrayI   @[@"fds",@"fsd"]方式創(chuàng)建多于1個(gè)元素 或者 arrayWith創(chuàng)建都是__NSArrayI



//__NSArray0
//arr@[11]   調(diào)用的是  [__NSArray0 objectAtIndex:]

//__NSSingleObjectArrayI
//arr@[11] 調(diào)用的是  [__NSSingleObjectArrayI objectAtIndex:]

//不可變數(shù)組
// <  iOS11: arr@[11]  調(diào)用的是[__NSArrayI objectAtIndex:]
// >= iOS11: arr@[11]  調(diào)用的是[__NSArrayI objectAtIndexedSubscript]
//  任意系統(tǒng)   [arr objectAtIndex:111]  調(diào)用的都是[__NSArrayM objectAtIndex:]

//可變數(shù)組
// <  iOS11: arr@[11]  調(diào)用的是[__NSArrayM objectAtIndex:]
// >= iOS11: arr@[11]  調(diào)用的是[__NSArrayM objectAtIndexedSubscript]
//  任意系統(tǒng)   [arr objectAtIndex:111]  調(diào)用的都是[__NSArrayI objectAtIndex:]
[self safe_exchangeInstanceMethod:objc_getClass("__NSPlaceholderArray") originalSel:@selector(initWithObjects:count:) newSel:@selector(safe_initWithObjects:count:)];  
[self safe_exchangeInstanceMethod:objc_getClass("__NSArrayI") originalSel:@selector(objectAtIndex:) newSel:@selector(safe_objectAtIndexI:)];
[self safe_exchangeInstanceMethod:objc_getClass("__NSArrayI") originalSel:@selector(objectAtIndexedSubscript:) newSel:@selector(safe_objectAtIndexedSubscriptI:)];
[self safe_exchangeInstanceMethod:objc_getClass("__NSArray0") originalSel:@selector(objectAtIndex:) newSel:@selector(safe_objectAtIndex0:)];
[self safe_exchangeInstanceMethod:objc_getClass("__NSSingleObjectArrayI") originalSel:@selector(objectAtIndex:) newSel:@selector(safe_objectAtIndexSI:)];
   //方法交換只要一次就好
   Class dClass=NSClassFromString(@"__NSArrayM");
   //由于低于11.0交換此方法會(huì)導(dǎo)致有鍵盤顯示的地方,此時(shí)退到后臺(tái)會(huì)crash [UIKeyboardLayoutStar release]: message sent to deallocated instance 0x7fd762cc11f0
     if ([UIDevice currentDevice].systemVersion.doubleValue>=11.0) {
          [self safe_exchangeInstanceMethod:dClass originalSel:@selector(objectAtIndex:) newSel:@selector(safe_objectAtIndexM:)];
       }
      //因?yàn)?1.0以上系統(tǒng)才會(huì)調(diào)用此方法,所以大于11.0才交換此方法
     if([UIDevice currentDevice].systemVersion.doubleValue>=11.0){
            [self safe_exchangeInstanceMethod:dClass originalSel:@selector(objectAtIndexedSubscript:) newSel:@selector(safe_objectAtIndexedSubscriptM:)];
        }
        
      [self safe_exchangeInstanceMethod:dClass originalSel:@selector(insertObject:atIndex:) newSel:@selector(safe_insertObject:atIndex:)];
      [self safe_exchangeInstanceMethod:dClass originalSel:@selector(removeObjectAtIndex:) newSel:@selector(safe_removeObjectAtIndex:)];
      [self safe_exchangeInstanceMethod:dClass originalSel:@selector(replaceObjectAtIndex:withObject:) newSel:@selector(safe_replaceObjectAtIndex:withObject:)];
4.字典賦值key或value為nil
/*
 大概和NSArray類似  也是iOS8之前都是__NSDictionaryI,其他的參考NSArray
 
 __NSSingleEntryDictionaryI
 @{@"key":@"value"} 此種形式創(chuàng)建而且僅一個(gè)可以為__NSSingleEntryDictionaryI
 __NSDictionaryM
 NSMutableDictionary創(chuàng)建都為__NSDictionaryM
 __NSDictionary0
 除__NSDictionaryM外 不管什么方式創(chuàng)建0個(gè)key都為__NSDictionary0
 __NSDictionaryI
 @{@"key":@"value",@"key2",@"value2"}此種方式創(chuàng)建多于1個(gè)key,或者initWith創(chuàng)建都是__NSDictionaryI

 NSMutableDictionary通過下標(biāo)方式賦值的時(shí)候,value為nil不會(huì)崩潰
    iOS11之前會(huì)調(diào)用 setObject:forKey
    iOS11之后(含11)  setObject:forKeyedSubscript:
 */
 [self safe_exchangeInstanceMethod:NSClassFromString(@"__NSPlaceholderDictionary") originalSel:@selector(initWithObjects:forKeys:count:) newSel:@selector(safe_initWithObjects:forKeys:count:)];
 [self safe_exchangeInstanceMethod:NSClassFromString(@"__NSPlaceholderDictionary") originalSel:@selector(initWithObjects:forKeys:) newSel:@selector(safe_initWithObjects:forKeys:)]; 
   Class dClass=NSClassFromString(@"__NSDictionaryM");
   [self safe_exchangeInstanceMethod:dClass originalSel:@selector(setObject:forKey:) newSel:@selector(safe_setObject:forKey:)];
   [self safe_exchangeInstanceMethod:dClass originalSel:@selector(setObject:forKeyedSubscript:) newSel:@selector(safe_setObject:forKeyedSubscript:)];
   [self safe_exchangeInstanceMethod:dClass originalSel:@selector(removeObjectForKey:) newSel:@selector(safe_removeObjectForKey:)];
5.NSString substringFromIndex 越界問題
        Class dClass=NSClassFromString(@"__NSCFConstantString");
        Class NSPlaceholderStringClass=NSClassFromString(@"NSPlaceholderString");
        
        //initWithString:
        [self safe_exchangeInstanceMethod:NSPlaceholderStringClass originalSel:@selector(initWithString:) newSel:@selector(safe_initWithString:)];
        
        //hasPrefix
        [self safe_exchangeInstanceMethod:dClass originalSel:@selector(hasPrefix:) newSel:@selector(safe_hasPrefix:)];
        
       //hasSuffix
        [self safe_exchangeInstanceMethod:dClass originalSel:@selector(hasSuffix:) newSel:@selector(safe_hasSuffix:)];
        
        //substringFromIndex
        [self safe_exchangeInstanceMethod:dClass originalSel:@selector(substringFromIndex:) newSel:@selector(safe_substringFromIndex:)];
        
        //substringToIndex
        [self safe_exchangeInstanceMethod:dClass originalSel:@selector(substringToIndex:) newSel:@selector(safe_substringToIndex:)];
        
        //substringWithRange
         [self safe_exchangeInstanceMethod:dClass originalSel:@selector(substringWithRange:) newSel:@selector(safe_substringWithRange:)];
        
        //characterAtIndex
         [self safe_exchangeInstanceMethod:dClass originalSel:@selector(characterAtIndex:) newSel:@selector(safe_characterAtIndex:)];
        
         //stringByReplacingOccurrencesOfString:withString:options:range:
        [self safe_exchangeInstanceMethod:dClass originalSel:@selector(stringByReplacingOccurrencesOfString:withString:options:range:) newSel:@selector(safe_stringByReplacingOccurrencesOfString:withString:options:range:)];
        
        //stringByReplacingCharactersInRange:withString:
         [self safe_exchangeInstanceMethod:dClass originalSel:@selector(stringByReplacingCharactersInRange:withString:) newSel:@selector(safe_stringByReplacingCharactersInRange:withString:)];
  
        Class dClass=NSClassFromString(@"__NSCFString");
        Class NSPlaceholderMutableStringClass=NSClassFromString(@"NSPlaceholderMutableString");
        
        //initWithString:
        [self safe_exchangeInstanceMethod:NSPlaceholderMutableStringClass originalSel:@selector(initWithString:) newSel:@selector(safe_initWithString:)];
        
        
        //hasPrefix
        [self safe_exchangeInstanceMethod:dClass originalSel:@selector(hasPrefix:) newSel:@selector(safe_hasPrefix:)];
        
        //hasSuffix
        [self safe_exchangeInstanceMethod:dClass originalSel:@selector(hasSuffix:) newSel:@selector(safe_hasSuffix:)];
        
        
        //substringFromIndex
        [self safe_exchangeInstanceMethod:dClass originalSel:@selector(substringFromIndex:) newSel:@selector(safe_substringFromIndex:)];
        
        //substringToIndex
        [self safe_exchangeInstanceMethod:dClass originalSel:@selector(substringToIndex:) newSel:@selector(safe_substringToIndex:)];
        
        //substringWithRange
        [self safe_exchangeInstanceMethod:dClass originalSel:@selector(substringWithRange:) newSel:@selector(safe_substringWithRange:)];
        
        //characterAtIndex
        [self safe_exchangeInstanceMethod:dClass originalSel:@selector(characterAtIndex:) newSel:@selector(safe_characterAtIndex:)];
        
        
        //stringByReplacingOccurrencesOfString:withString:options:range:
        [self safe_exchangeInstanceMethod:dClass originalSel:@selector(stringByReplacingOccurrencesOfString:withString:options:range:) newSel:@selector(safe_stringByReplacingOccurrencesOfString:withString:options:range:)];
        
        
        //stringByReplacingCharactersInRange:withString:
        [self safe_exchangeInstanceMethod:dClass originalSel:@selector(stringByReplacingCharactersInRange:withString:) newSel:@selector(safe_stringByReplacingCharactersInRange:withString:)];
        
        
        
        //replaceCharactersInRange:withString:
        [self safe_exchangeInstanceMethod:dClass originalSel:@selector(replaceCharactersInRange:withString:) newSel:@selector(safe_replaceCharactersInRange:withString:)];
        
        //replaceOccurrencesOfString:withString:options:range:
        [self safe_exchangeInstanceMethod:dClass originalSel:@selector(replaceOccurrencesOfString:withString:options:range:) newSel:@selector(safe_replaceOccurrencesOfString:withString:options:range:)];
        
        //insertString:atIndex:
        [self safe_exchangeInstanceMethod:dClass originalSel:@selector(insertString:atIndex:) newSel:@selector(safe_insertString:atIndex:)];
        
        //deleteCharactersInRange:
        [self safe_exchangeInstanceMethod:dClass originalSel:@selector(deleteCharactersInRange:) newSel:@selector(safe_deleteCharactersInRange:)];
        
        
        //appendString:
        [self safe_exchangeInstanceMethod:dClass originalSel:@selector(appendString:) newSel:@selector(safe_appendString:)];
        
        
        //setString:
        [self safe_exchangeInstanceMethod:dClass originalSel:@selector(setString:) newSel:@selector(safe_setString:)];
        
6.NSAttributedString initWithString stirng=nil問題
       Class dClass = NSClassFromString(@"NSConcreteAttributedString");
        
        //initWithString:
        [self safe_exchangeInstanceMethod:dClass originalSel:@selector(initWithString:) newSel:@selector(safe_initWithString:)];
        
        //initWithAttributedString
        [self safe_exchangeInstanceMethod:dClass originalSel:@selector(initWithString:attributes:) newSel:@selector(safe_initWithString:attributes:)];
        
        //initWithString:attributes:
        [self safe_exchangeInstanceMethod:dClass originalSel:@selector(initWithAttributedString:) newSel:@selector(safe_initWithAttributedString:)];
       Class dClass = NSClassFromString(@"NSConcreteMutableAttributedString");
        
        //initWithString:
        [self safe_exchangeInstanceMethod:dClass originalSel:@selector(initWithString:) newSel:@selector(safe_initWithString:)];
        
        //initWithAttributedString
        [self safe_exchangeInstanceMethod:dClass originalSel:@selector(initWithString:attributes:) newSel:@selector(safe_initWithString:attributes:)];
        
        //initWithString:attributes:
        [self safe_exchangeInstanceMethod:dClass originalSel:@selector(initWithAttributedString:) newSel:@selector(safe_initWithAttributedString:)];
        
        
        //以下為NSMutableAttributedString特有方法
        //4.replaceCharactersInRange:withString:
        [self safe_exchangeInstanceMethod:dClass originalSel:@selector(replaceCharactersInRange:withString:) newSel:@selector(safe_replaceCharactersInRange:withString:)];
        
        //5.setAttributes:range:
        [self safe_exchangeInstanceMethod:dClass originalSel:@selector(setAttributes:range:) newSel:@selector(safe_setAttributes:range:)];
        
        
        
        //6.addAttribute:value:range:
        [self safe_exchangeInstanceMethod:dClass originalSel:@selector(addAttribute:value:range:) newSel:@selector(safe_addAttribute:value:range:)];
        
        //7.addAttributes:range:
        [self safe_exchangeInstanceMethod:dClass originalSel:@selector(addAttributes:range:) newSel:@selector(safe_addAttributes:range:)];
        
        //8.removeAttribute:range:
        [self safe_exchangeInstanceMethod:dClass originalSel:@selector(removeAttribute:range:) newSel:@selector(safe_removeAttribute:range:)];
        
        //9.replaceCharactersInRange:withAttributedString:
        [self safe_exchangeInstanceMethod:dClass originalSel:@selector(replaceCharactersInRange:withAttributedString:) newSel:@selector(safe_replaceCharactersInRange:withAttributedString:)];
        
        
        //10.insertAttributedString:atIndex:
        [self safe_exchangeInstanceMethod:dClass originalSel:@selector(insertAttributedString:atIndex:) newSel:@selector(safe_insertAttributedString:atIndex:)];
        
        
        //11.appendAttributedString:
        [self safe_exchangeInstanceMethod:dClass originalSel:@selector(appendAttributedString:) newSel:@selector(safe_appendAttributedString:)];
        
        //12.deleteCharactersInRange:
        [self safe_exchangeInstanceMethod:dClass originalSel:@selector(deleteCharactersInRange:) newSel:@selector(safe_deleteCharactersInRange:)];
        
        //13.setAttributedString:
        [self safe_exchangeInstanceMethod:dClass originalSel:@selector(setAttributedString:) newSel:@selector(safe_setAttributedString:)];
        
7.通知deallooc時(shí)為移除問題

dealloc時(shí)不管通知中心添沒添加自己,都移除

此框架可以捕獲到異常,以及未移除的kvo,打印出信息,回調(diào)給用戶,用戶可以上傳到bugly等crash統(tǒng)計(jì)平臺(tái)

//注意線上環(huán)境isDebug一定要設(shè)置為NO)
[LSSafeProtector openSafeProtectorWithIsDebug:YES block:^(NSException *exception, LSSafeProtectorCrashType crashType) {
//[Bugly reportException:exception];

//此方法相對(duì)于上面的方法,好處在于bugly后臺(tái)查看bug崩潰位置時(shí),不用點(diǎn)擊跟蹤數(shù)據(jù),再點(diǎn)擊crash_attach.log,查看里面的額外信息來查看崩潰位置
[Bugly reportExceptionWithCategory:3 name:exception.name reason:[NSString stringWithFormat:@"%@  崩潰位置:%@",exception.reason,exception.userInfo[@"location"]] callStack:@[exception.userInfo[@"callStackSymbols"]] extraInfo:exception.userInfo terminateApp:NO];
}];

具體代碼demo請(qǐng)查看github https://github.com/lsmakethebest/LSSafeProtector

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容