iOS如何防止crash,并上传bugly

本文详细介绍了iOS开发中遇到的常见crash种类,包括unSelector方法未找到、KVO未正确移除、数组越界、字典赋值key或value为nil等问题,并提供了相应的解决方案。此外,还分享了如何使用消息转发、交换方法等技术来避免这些crash问题,确保应用的稳定运行。

1.程序中常见的crash种类有

  • 1.unSelector 方法未找到
  • 2.KVO未移除,多次添加,多次移除问题
  • 3.数组越界
  • 4.字典赋值key或value为nil
  • 5.NSString substringFromIndex 越界问题
  • 6.NSAttributedString initWithString stirng=nil问题
  • 7.通知deallooc时为移除问题

2.解决方案

1.unSelector可以利用消息转发来解决

消息转发有三种时机
- 1.在resolveInstanceMethod方法里,添加方法,但是此种方式损害了原有类的结构

+(BOOL)resolveInstanceMethod:(SEL)sel
{
    return YES;
}
  • 2.在下面方法里放回一个自定义对象,同时给此对象添加未实现的方法
-(id)forwardingTargetForSelector:(SEL)aSelector
{
    rerurn obj;
}

3.完整转发,对方法进行签名,自定义对象然后invoke
- 这里采用第3种方式,生成方法签名,然后forwardInvocation,这里self invoke,因为self没有此方法会捕获到异常,避免程序崩溃

[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:未实现
  • 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记录有哪些人监听了自己,用safe_upObservedArray记录自己监听了哪些对象,用来在addObserver时判断是否添加过了,removeObserver时是否已经移除过了,或者压根没有添加过不能移除,在dealloc时自动移除,交换observeValueForKeyPath:ofObject:change:context方法避免监听者未实现此方法

3.数组越界 ,交换数组的一些方法,需要注意的就是数组有类簇,所以需要交换多个类,根据以下规则交换方法即可
// < = iOS 8:下都是__NSArrayI
//iOS9 @[] 是__NSArray0  @[@"fd"]是__NSArrayI
//iOS10以后(含10): 分 __NSArrayI、  __NSArray0、__NSSingleObjectArrayI


//__NSArrayM   NSMutableArray创建的都为__NSArrayM
//__NSArray0   除__NSArrayM 0个元素都为__NSArray0
// __NSSingleObjectArrayI @[@"fds"]只有此形式创建而且仅一个元素为__NSSingleObjectArrayI
//__NSArrayI   @[@"fds",@"fsd"]方式创建多于1个元素 或者 arrayWith创建都是__NSArrayI



//__NSArray0
//arr@[11]   调用的是  [__NSArray0 objectAtIndex:]

//__NSSingleObjectArrayI
//arr@[11] 调用的是  [__NSSingleObjectArrayI objectAtIndex:]

//不可变数组
// <  iOS11: arr@[11]  调用的是[__NSArrayI objectAtIndex:]
// >= iOS11: arr@[11]  调用的是[__NSArrayI objectAtIndexedSubscript]
//  任意系统   [arr objectAtIndex:111]  调用的都是[__NSArrayM objectAtIndex:]

//可变数组
// <  iOS11: arr@[11]  调用的是[__NSArrayM objectAtIndex:]
// >= iOS11: arr@[11]  调用的是[__NSArrayM objectAtIndexedSubscript]
//  任意系统   [arr objectAtIndex:111]  调用的都是[__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交换此方法会导致有键盘显示的地方,此时退到后台会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:)];
       }
      //因为11.0以上系统才会调用此方法,所以大于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"} 此种形式创建而且仅一个可以为__NSSingleEntryDictionaryI
 __NSDictionaryM
 NSMutableDictionary创建都为__NSDictionaryM
 __NSDictionary0
 除__NSDictionaryM外 不管什么方式创建0个key都为__NSDictionary0
 __NSDictionaryI
 @{@"key":@"value",@"key2",@"value2"}此种方式创建多于1个key,或者initWith创建都是__NSDictionaryI

 NSMutableDictionary通过下标方式赋值的时候,value为nil不会崩溃
    iOS11之前会调用 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时为移除问题

dealloc时不管通知中心添没添加自己,都移除

此框架可以捕获到异常,以及未移除的kvo,打印出信息,回调给用户,用户可以上传到bugly等crash统计平台

//注意线上环境isDebug一定要设置为NO)
[LSSafeProtector openSafeProtectorWithIsDebug:YES block:^(NSException *exception, LSSafeProtectorCrashType crashType) {
//[Bugly reportException:exception];

//此方法相对于上面的方法,好处在于bugly后台查看bug崩溃位置时,不用点击跟踪数据,再点击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请查看github https://github.com/lsmakethebest/LSSafeProtector

<think>我们正在回答用户关于“如何使用BuglyiOS平台上定位崩溃问题”的询问。根据用户提供的引用内容,我们需要整合信息给出清晰的步骤。用户提供的引用[1]说明了如何触发一个Crash查看Crashissue,引用[2]则详细说明了如何通过反向符号化来定位崩溃原因。因此,我们的回答应该包括两个主要部分:1.如何集成Bugly触发Crash来上报崩溃信息(简要提及,因为用户可能已经完成集成,重点在定位)。2.如何通过Bugly上报的崩溃日志进行反向符号化以定位崩溃的源代码位置。注意:用户的问题集中在定位崩溃的方法和步骤,所以重点在第二部分。根据引用[2],反向符号化的步骤需要dSYM文件,且需要执行终端命令。我们将详细描述这些步骤。另外,我们还需要生成相关问题,以帮助用户深入了解。回答结构:1.引言:简述Bugly崩溃定位中的作用。2.步骤一:在Bugly控制台查看崩溃报告(包括堆栈信息)。3.步骤二:准备反向符号化所需的材料(dSYM文件、崩溃日志中的基地址和地址)。4.步骤三:使用atos命令进行反向符号化。5.步骤四:解释结果,定位代码行。6.注意事项:如dSYM文件的管理等。最后,生成相关问题。注意:由于用户提供的引用内容中已经包含了具体的命令和步骤,我们直接整理清晰表述即可。</think>### iOS Bugly 定位崩溃的方法和步骤 在 iOS 平台使用 Bugly 定位崩溃问题主要分为两个阶段:**崩溃上报**和**符号化解析**。以下是详细操作流程: #### 一、崩溃上报阶段 1. **集成 Bugly SDK** 在 AppDelegate 中初始化 Bugly(需提前在 Bugly 官网创建应用获取 AppID): ```swift func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { Bugly.start(withAppId: "YOUR_APP_ID") return true } ``` 2. **触发崩溃测试**(可选) 添加测试代码模拟崩溃(正式环境需移除): ```swift @IBAction func triggerCrash(_ sender: UIButton) { let array = [0] _ = array[1] // 故意触发数组越界崩溃 } ``` 崩溃后 10 秒内可在 [Bugly 控制台](https://bugly.qq.com/) 的「崩溃」页面查看原始报告[^1]。 --- #### 二、符号化解析阶段(关键步骤) 崩溃日志中的地址需要反向符号化才能定位到源代码,需准备: - **dSYM 文件**:Xcode 编译生成的调试符号文件(位于 `~/Library/Developer/Xcode/Archives`) - **崩溃日志中的关键信息**:内存基地址(Image Base Address)和崩溃地址(Crash Address) **操作流程**: 1. **获取崩溃地址信息** 在 Bugly 崩溃详情页的「堆栈跟踪」中找到类似: ``` 0 CoreFoundation 0x000000018d3e3d98 0x18d2c0000 + 0x123d98 ↑ 模块名 ↑ 崩溃地址 ↑ 内存基地址 ``` 2. **终端执行符号化命令** ```bash cd /Applications/Xcode.app/Contents/Developer ./usr/bin/atos -o [dSYM文件路径]/Contents/Resources/DWARF/[应用名] \ -l [内存基地址] [崩溃地址] ``` **示例**: ```bash ./usr/bin/atos -o ~/Desktop/YourApp.dSYM/Contents/Resources/DWARF/YourApp \ -l 0x18d2c0000 0x000000018d3e3d98 ``` 3. **解析结果** 成功执行后将输出源码位置: ``` -[ViewController triggerCrash:] (in YourApp) (ViewController.swift:25) ``` 表示崩溃发生在 `ViewController.swift` 第 25 行[^2]。 --- #### 注意事项 1. **dSYM 文件匹配** - 必须使用**对应版本编译生成的 dSYM**(UUID 需与崩溃日志一致) - 可在终端验证 UUID:`dwarfdump --uuid YourApp.dSYM` 2. **自动化方案** - 在 Bugly 控制台上传 dSYM 文件(「符号表管理」>「上传」),后续崩溃会自动符号化 - 或通过 CI 脚本自动上传: ```bash curl -k "https://api.bugly.qq.com/openapi/file/upload/symbol?app_key=KEY&app_id=ID" \ --form "api_version=1" \ --form "app_id=APP_ID" \ --form "symbolType=2" \ --form "bundleId=com.your.bundle" \ --form "fileName=your_app.dSYM.zip" \ --form "file=@your_app.dSYM.zip" ``` 3. **调试技巧** - 开发阶段开启 Xcode 的 **Exception Breakpoint** 实时捕获崩溃 - 真机测试时连接 Xcode → **Window → Devices and Simulators** 查看设备日志 > **关键原理**:dSYM 文件将机器码地址映射到源代码位置,反向符号化是定位崩溃的必要步骤[^2]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值