攻略1-11:处理异常

1、添加一个按钮动作

- (IBAction)throwFakeException:(UIButton *)sender {
    NSException * e = [[NSException alloc] initWithName:@"FakeException" reason:@"The developer sucks!" userInfo:[NSDictionary dictionaryWithObject:@"Extra info" forKey:@"Key"]];
    [e raise];
}

2、通过NSSetUncaughtException函数注册一个处理函数,这个函数是一个void函数,接受一个NSException引用为唯一参数。

//
//  AppDelegate.m
//  ErrorHanding
//
//  Created by 冯敏 on 16/4/29.
//  Copyright © 2016年 fengmin. All rights reserved.
//

#import "AppDelegate.h"
#import <MessageUI/MessageUI.h>
#import <MessageUI/MFMailComposeViewController.h>

@interface AppDelegate ()<UIAlertViewDelegate, MFMailComposeViewControllerDelegate>

@end

@implementation AppDelegate

void exceptionHandler(NSException * exception)
{
    NSLog(@"Uncaught exception:%@
Reason:%@
User Info:%@
Call Stack:%@",exception.name,exception.reason,exception.userInfo,exception.callStackSymbols);
    
    //Set flag
    NSUserDefaults * settings = [NSUserDefaults standardUserDefaults];
    [settings setBool:YES forKey:@"ExceptionOccurredOnLastRun"];
    [settings synchronize];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

//预定义的条件宏,使得只有当应用程序运行在真实设备上的时候才使用我们的异常处理代码。
#if !TARGET_IPHONE_SIMULATOR //Default excepion handling code NSUserDefaults * settings = [NSUserDefaults standardUserDefaults]; if ([settings boolForKey:@"ExceptionOccurredOnLastRun"]) { //Reset exception occurred flag [settings setBool:NO forKey:@"ExceptionOccurredOnLastRunKey"]; [settings synchronize]; //Notify the user UIAlertView * altert = [[UIAlertView alloc] initWithTitle:@"We are sorry!" message:@"An error occurred on the previous run!" delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil]; [altert addButtonWithTitle:@"Email a Report"]; [altert show]; }else{ //Register exception handle function NSSetUncaughtExceptionHandler(&exceptionHandler); //Redirect stderr output stream to file NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString * documentsPath = [paths objectAtIndex:0]; NSString * stderrPath = [documentsPath stringByAppendingPathComponent:@"stderr.log"]; freopen([stderrPath cStringUsingEncoding:NSASCIIStringEncoding], "w", stderr); } #endif return YES; } - (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex { NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString * documentsPath = [paths objectAtIndex:0]; NSString * stderrPath = [documentsPath stringByAppendingPathComponent:@"stderr.log"]; if (buttonIndex == 1) { //Email a Report MFMailComposeViewController * mailComposer = [[MFMailComposeViewController alloc] init]; mailComposer.mailComposeDelegate = self; [mailComposer setSubject:@"Error Report"]; [mailComposer setToRecipients:[NSArray arrayWithObject:@"support@mycompany.com"]]; //Attach log file NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString * documentsPath = [paths objectAtIndex:0]; NSString * stderrPaht = [documentsPath stringByAppendingPathComponent:@"stderr.log"]; NSData * data = [NSData dataWithContentsOfFile:stderrPath]; [mailComposer addAttachmentData:data mimeType:@"Text/XML" fileName:@"stderr.log"]; UIDevice * device = [UIDevice currentDevice]; NSString * emailBody = [NSString stringWithFormat:@"My Model:%@ My OS:%@ My Version:%@",device.model,device.systemName,device.systemVersion]; [mailComposer setMessageBody:emailBody isHTML:NO]; [self.window.rootViewController presentViewController:mailComposer animated:YES completion:^{ }]; } NSSetUncaughtExceptionHandler(&exceptionHandler); //Redirect stderr output stream to file freopen([stderrPath cStringUsingEncoding:NSASCIIStringEncoding], "w", stderr); } - (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error { [self.window.rootViewController dismissViewControllerAnimated:YES completion:^{ }]; }
原文地址:https://www.cnblogs.com/fengmin/p/5455057.html