虽然大家都不愿意看到程序崩溃,但可能崩溃是每个应用必须面对的现实,既然崩溃已经发生,无法阻挡了,那我们就让它崩也崩得淡定点吧。

IOS SDK中提供了一个现成的函数 NSSetUncaughtExceptionHandler 用来做异常处理,但功能非常有限,而引起崩溃的大多数原因如:内存访问错误,重复释放等错误就无能为力了,因为这种错误它抛出的是Signal,所以必须要专门做Signal处理。首先定义一个UncaughtExceptionHandler类,代码如下:

#import <Foundation/Foundation.h>

#import <UIKit/UIKit.h>

@interface UncaughtExceptionHandler : NSObject

{

BOOL dismissed;

}

+(void) InstallUncaughtExceptionHandler;

@end

//利用 NSSetUncaughtExceptionHandler,当程序异常退出的时候,可以先进行处理,然后做一些自定义的动作,比如下面一段代码,就是网上有人写的,直接在发生异常时给某人发送邮件,</span>

void UncaughtExceptionHandlers (NSException *exception);

#import "UncaughtExceptionHandler.h"

#include <libkern/OSAtomic.h>

#include <execinfo.h>

NSString * const UncaughtExceptionHandlerSignalExceptionName = @"UncaughtExceptionHandlerSignalExceptionName";

NSString * const UncaughtExceptionHandlerSignalKey = @"UncaughtExceptionHandlerSignalKey";

NSString * const UncaughtExceptionHandlerAddressesKey = @"UncaughtExceptionHandlerAddressesKey";

volatile int32_t UncaughtExceptionCount = 0;

const int32_t UncaughtExceptionMaximum = 10;

const NSInteger UncaughtExceptionHandlerSkipAddressCount = 4;

const NSInteger UncaughtExceptionHandlerReportAddressCount = 5;

NSString* getAppInfo()

{

NSString *appInfo = [NSString stringWithFormat:@"App : %@ %@(%@)\nDevice : %@\nOS Version : %@ %@\n",

[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"],

[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"],

[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"],

[UIDevice currentDevice].model,

[UIDevice currentDevice].systemName,

[UIDevice currentDevice].systemVersion];

//     [UIDevice currentDevice].uniqueIdentifier];

NSLog(@"Crash!!!! %@", appInfo);

return appInfo;

}

void MySignalHandler(int signal)

{

int32_t exceptionCount = OSAtomicIncrement32(&UncaughtExceptionCount);

if (exceptionCount > UncaughtExceptionMaximum)

{

return;

}

if(signal==11)

{//比较坑爹的是 我遇到的一个问题只有iPhone5出现问题 但是我这边测试的没有iPhone5 无法直接log  可能是内存不足 果然 删除几个应用就可以了 所以加了这句

UIAlertView * tip2 = [[UIAlertView alloc]initWithTitle:@"可能原因:key" message:@"内存不足" delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil];

[tip2 show];

[tip2 release];

}

NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithObject:[NSNumber numberWithInt:signal] forKey:UncaughtExceptionHandlerSignalKey];

NSArray *callStack = [UncaughtExceptionHandler backtrace];

[userInfo setObject:callStack forKey:UncaughtExceptionHandlerAddressesKey];

[[[[UncaughtExceptionHandler alloc] init] autorelease]

performSelectorOnMainThread:@selector(handleException:)

withObject:

[NSException

exceptionWithName:UncaughtExceptionHandlerSignalExceptionName

reason:

[NSString stringWithFormat:

NSLocalizedString(@"Signal %d was raised.\n"

@"%@", nil),

signal, getAppInfo()]

userInfo:

[NSDictionary

dictionaryWithObject:[NSNumber numberWithInt:signal]

forKey:UncaughtExceptionHandlerSignalKey]]

waitUntilDone:YES];

}

@implementation UncaughtExceptionHandler

+(void) InstallUncaughtExceptionHandler

{

signal(SIGABRT, MySignalHandler);

signal(SIGILL, MySignalHandler);

signal(SIGSEGV, MySignalHandler);

signal(SIGFPE, MySignalHandler);

signal(SIGBUS, MySignalHandler);

signal(SIGPIPE, MySignalHandler);

}

+ (NSArray *)backtrace

{

void* callstack[128];

int frames = backtrace(callstack, 128);

char **strs = backtrace_symbols(callstack, frames);

int i;

NSMutableArray *backtrace = [NSMutableArray arrayWithCapacity:frames];

for (

i = UncaughtExceptionHandlerSkipAddressCount;

i < UncaughtExceptionHandlerSkipAddressCount +

UncaughtExceptionHandlerReportAddressCount;

i++)

{

[backtrace addObject:[NSString stringWithUTF8String:strs[i]]];

}

free(strs);

return backtrace;

}

- (void)alertView:(UIAlertView *)anAlertView clickedButtonAtIndex:(NSInteger)anIndex

{

if (anIndex == 0)

{

dismissed = YES;

}

}

- (void)handleException:(NSException *)exception

{

UIAlertView *alert =

[[[UIAlertView alloc]

initWithTitle:NSLocalizedString(@"Unhandled exception", nil)

message:[NSString stringWithFormat:NSLocalizedString(

@"You can try to continue but the application may be unstable.\n"

@"%@\n%@", nil),

[exception reason],

[[exception userInfo] objectForKey:UncaughtExceptionHandlerAddressesKey]]

delegate:self

cancelButtonTitle:NSLocalizedString(@"Quit", nil)

otherButtonTitles:NSLocalizedString(@"Continue", nil), nil]

autorelease];

[alert show];

CFRunLoopRef runLoop = CFRunLoopGetCurrent();

CFArrayRef allModes = CFRunLoopCopyAllModes(runLoop);

while (!dismissed)

{

for (NSString *mode in (NSArray *)allModes)

{

CFRunLoopRunInMode((CFStringRef)mode, 0.001, false);

}

}

CFRelease(allModes);

NSSetUncaughtExceptionHandler(NULL);

signal(SIGABRT, SIG_DFL);

signal(SIGILL, SIG_DFL);

signal(SIGSEGV, SIG_DFL);

signal(SIGFPE, SIG_DFL);

signal(SIGBUS, SIG_DFL);

signal(SIGPIPE, SIG_DFL);

if ([[exception name] isEqual:UncaughtExceptionHandlerSignalExceptionName])

{

kill(getpid(), [[[exception userInfo] objectForKey:UncaughtExceptionHandlerSignalKey] intValue]);

}

else

{

[exception raise];

}

}

void UncaughtExceptionHandlers (NSException *exception) {

NSArray *arr = [exception callStackSymbols];

NSString *reason = [exception reason];

NSString *name = [exception name];

NSString *urlStr = [NSString stringWithFormat:@"mailto://1140454645@qq.com?subject=bug报告&body=感谢您的配合!<br><br><br>"

"错误详情:<br>%@<br>--------------------------<br>%@<br>---------------------<br>%@",

name,reason,[arr componentsJoinedByString:@"<br>"]];

NSURL *url = [NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

[[UIApplication sharedApplication] openURL:url];

//或者直接用代码,输入这个崩溃信息,以便在console中进一步分析错误原因

NSLog(@"1heqin, CRASH: %@", exception);

NSLog(@"heqin, Stack Trace: %@", [exception callStackSymbols]);

}

@end

然后在delegate文件里面- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions函数里面

[UncaughtExceptionHandler InstallUncaughtExceptionHandler];

NSSetUncaughtExceptionHandler (&UncaughtExceptionHandlers);

异常捕获拒绝闪退 让应用从容的崩溃UncaughtExceptionHandler的更多相关文章

  1. 【IOS】异常捕获 拒绝闪退 让应用从容的崩溃 UncaughtExceptionHandler

    尽管大家都不愿意看到程序崩溃,但可能崩溃是每一个应用必须面对的现实.既然崩溃已经发生.无法阻挡了.那我们就让它崩也崩得淡定点吧. IOS SDK中提供了一个现成的函数 NSSetUncaughtExc ...

  2. 阿里客户端工程师试题简析——Android应用的闪退(crash)分析

    1. 问题描述 闪退(Crash)是客户端程序在运行时遭遇无法处理的异常或错误时而退出应用程序的表现,请从crash发生的原因分类与解决方法.在出现crash后如何捕捉并分析异常这两个问题给出自己的解 ...

  3. iOS 启动连续闪退保护方案

    引言 “如果某个实体表现出以下任何一种特性,它就具备自主性:自我修复.自我保护.自我维护.对目标的自我控制.自我改进.” —— 凯文·凯利 iOS App 有时可能遇到启动必 crash 的绝境:每次 ...

  4. 阿里安卓面试分析: Android应用的闪退(crash)问题跟踪和解析

    一:问题描述    闪退(Crash)是客户端程序在运行时遭遇无法处理的异常或错误时而退出应用程序的表现,请从crash发生的原因分类与解决方法.在出现crash后如何捕捉并分析异常这两个问题给出自己 ...

  5. 异常捕获 崩溃 Bugly ACRC 简介 总结 MD

    Markdown版本笔记 我的GitHub首页 我的博客 我的微信 我的邮箱 MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina ...

  6. 异常记录——bat批处理闪退

    bat批处理闪退 bat描述 我的博客每次更新需要跑多个命令 clean(清除旧文)+g(生成新文)+d(部署到服务器),作为一个懒惰的程序员,自然要写一个bat一键完成 E: cd blog hex ...

  7. 华为手机 android8.0APP更新时出现安装包解析异常的提示及安装闪退(无反应)问题

    在做android app升级更新时遇到几个问题,我用的测试机是华为V10 系统为8.0 一.安装闪退(无反应) 解决办法: 只要在Mainfest.xml 中加入权限编码即可解决 <uses- ...

  8. 印象最深的一个bug——排查修复问题事件BEX引发的谷歌浏览器闪退崩溃异常

    前言 最近,我们部门负责项目运维的小王频频接到甲方的反馈,运行的项目使用谷歌浏览器登录后,每次点击处理2秒后,浏览器自动闪退崩溃.小王同学折腾了一个星期,还没找到问题的原因.甲方客户都把问题反馈给项目 ...

  9. iOS-应用闪退总结

    一.之前上架的 App 在 iOS 9 会闪退问题(iOS系统版本更新,未配置新版本导致闪退问题) 最新更新:(2015.10.02) 开发环境: Delphi 10 Seattle OS X El ...

随机推荐

  1. javascript语句语义大全(2)

    1. 四则运算相关 +,-,*,/,% 分别是加减乘除和取余 2.Math.pow(a,b) a的b次方 3.toFixed(a) 四舍五入为指定小数位数的数字 4. k++; ++K 看似相同但是在 ...

  2. pat L1-006. 连续因子

    L1-006. 连续因子 时间限制 400 ms 内存限制 65536 kB 代码长度限制 8000 B 判题程序 Standard 作者 陈越 一个正整数N的因子中可能存在若干连续的数字.例如630 ...

  3. java 参数传值

    基本数据类型参数的传值,参数为基本数据类型 class Computer{ int add(int x,int y){ return x+y; } } public class Example4_6 ...

  4. PAT (Advanced Level) 1115. Counting Nodes in a BST (30)

    简单题.统计一下即可. #include<cstdio> #include<cstring> #include<cmath> #include<vector& ...

  5. ThinkPHP使用方法

    1.下载ThinkPHP模板,整个导入到项目根目录下. 2.修改index.php文件,内容如下: <?php /***临时配置,项目完成开发后,这些配置会取消*******/define('A ...

  6. webapp之路--meta标签format-detection、apple-mobile-web-app-capable

    1. format-detection翻译成中文的意思是“格式检测”,顾名思义,它是用来检测html里的一些格式的,那关于meta的format-detection属性主要是有以下几个设置: meta ...

  7. angularjs中动态为audio绑定src

    今天在angularjs中用audio的时候碰到的这些问题,查阅http://www.cnblogs.com/rachelanlan/p/3598070.html获得解决,感谢! <div cl ...

  8. compileSdkVersion,buildToolsVersion还有targetSdkVersion要一致,从而避免build的时候报错

    Android Studio里的app的build.gradle文件: android { compileSdkVersion 24 buildToolsVersion "24.0.0&qu ...

  9. 安装psutil模块报错&安装python-devel

    psutil/_psutil_linux.c:9:20: 错误:Python.h:没有那个文件或目录 In file included from psutil/_psutil_linux.c:19:p ...

  10. (转)mahout中k-means例子的运行

           首先简单说明下,mahout下处理的文件必须是SequenceFile格式的,所以需要把txtfile转换成sequenceFile.SequenceFile是hadoop中的一个类,允 ...