攻略1-10:错误处理

1、创建一个新的NSObject子类.

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

#import <Foundation/Foundation.h>

@interface ErrorHandler : NSObject 

@property (nonatomic,strong) NSError * error;
@property (nonatomic) BOOL fatalError;

- (id)initWithError:(NSError *)error fatal:(BOOL)fatalError;
+ (void)handleError:(NSError *)error fatal:(BOOL)fatalError;

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

#import "ErrorHandler.h"
#import <UIKit/UIAlertView.h>

@interface ErrorHandler()<UIAlertViewDelegate>

@end

@implementation ErrorHandler 

static NSMutableArray * retainedDelegates = nil;

+ (void)handleError:(NSError *)error fatal:(BOOL)fatalError
{
    NSString * localizedCancelTitle = NSLocalizedString(@"Dismiss", nil);
    if (fatalError) {
        localizedCancelTitle = NSLocalizedString(@"Shut Down", nil);
    }
    
    ErrorHandler * errorHandle = [[ErrorHandler alloc] initWithError:error fatal:fatalError];
    if (!retainedDelegates) {
        retainedDelegates = [[NSMutableArray alloc] init];
    }
    [retainedDelegates addObject:errorHandle];
    
    UIAlertView * alter = [[UIAlertView alloc] initWithTitle:[error localizedDescription] message:[error localizedFailureReason] delegate:errorHandle cancelButtonTitle:localizedCancelTitle otherButtonTitles:nil];
    
    if ([error recoveryAttempter]) {
        alter.message = [NSString stringWithFormat:@"%@
%@",alter.message,error.localizedRecoverySuggestion];
        for (NSString * option in error.localizedRecoveryOptions) {
            [alter addButtonWithTitle:option];
        }
    }
    
    [alter show];
    NSLog(@"error:
%@,
userInfo:%@",error, [error userInfo]);
    
}
- (id)initWithError:(NSError *)error fatal:(BOOL)fatalError
{
    self = [super init];
    if (self) {
        self.error = error;
        self.fatalError = fatalError;
    }
    return self;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex != [alertView cancelButtonIndex]) {
        NSString * buttomTitle = [alertView buttonTitleAtIndex:buttonIndex];
        NSInteger recoveryIndex = [[self.error localizedRecoveryOptions] indexOfObject:buttomTitle];
        if (recoveryIndex != NSNotFound) {
            if ([[self.error recoveryAttempter] attemptRecoveryFromError:self.error optionIndex:recoveryIndex] == NO) {
                [ErrorHandler handleError:self.error fatal:self.fatalError];
            }
        }
    }else{
        //    if (self.fatalError) {
        //        abort();
        //    }
//        [retainedDelegates removeObject:self];
    }
}

@end

2、添加两个按钮

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

#import "ViewController.h"
#import "ErrorHandler.h"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)fakeNonFatalError:(UIButton *)sender {
    NSString * description = @"Connection Error";
    NSString * failureReason = @"Can't seem to get a connection.";
    NSArray * recoveryOptions = @[@"Retry"];
    NSString * recoverySuggestion = @"Check your wifi settings and retry.";
    NSDictionary * userInfo = [NSDictionary dictionaryWithObjects:@[description,failureReason,recoveryOptions,recoverySuggestion,self] forKeys:@[NSLocalizedDescriptionKey,NSLocalizedFailureReasonErrorKey,NSLocalizedRecoveryOptionsErrorKey,NSLocalizedRecoverySuggestionErrorKey,NSRecoveryAttempterErrorKey]];
    NSError * error = [[NSError alloc] initWithDomain:@"com.hans-eric.ios6recipesbook" code:100 userInfo:userInfo];
    [ErrorHandler handleError:error fatal:NO];
    
}

- (IBAction)fakeFatalError:(UIButton *)sender {
    NSString * description = @"Data Error";
    NSString * failureReason = @"Data is crrupt. The app must shut dowm.";
    NSString * recoverySuggestion = @"Contact support!";
    NSDictionary * userInfo = [NSDictionary dictionaryWithObjects:@[description,failureReason] forKeys:@[NSLocalizedDescriptionKey,NSLocalizedFailureReasonErrorKey]];
    NSError * error = [[NSError alloc] initWithDomain:@"com.hans-eric.ios6recipesbook" code:101 userInfo:userInfo];
    [ErrorHandler handleError:error fatal:YES];
}
原文地址:https://www.cnblogs.com/fengmin/p/5455003.html