zoukankan      html  css  js  c++  java
  • iOS开发错误处理技巧,PCH文件的使用,自定义NSNotification消息以及设置监听者(以Core Data处理数据时的错误为例)

    1.新建一个PCH文件,在该文件#import的头文件或者编写的代码,在整个项目中都有效

    2.在PCH文件中添加以下代码,请按照以下格式进行编写,包括每一行后面的反斜杠

    extern NSString * const ManagedObjectContextSaveDidFailNotification;

        #define FATAL_CORE_DATA_ERROR(__error__)

            NSLog(@"*** Fatal error in %s:%d %@ %@",

                __FILE__, __LINE__, error, [error userInfo]);          //在Debug区域显示错误信息

            [[NSNotificationCenter defaultCenter] postNotificationName:    //设置发送NSNotification消息

                ManagedObjectContextSaveDidFailNotification object:error];    

    3.在AppDelegate.m的didFinishLaunchingWithOptions方法中添加以下代码,让AppDelegate作为以上NSNotification消息的监听者,并在收到该消息时,调用fatalCoreDataError:方法

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(fatalCoreDataError:) name:ManagedObjectContextSaveDidFailNotification object:nil];

    4.在AppDelegate.m文件中添加以下代码,即弹出窗口让用户知道已经发生错误

    -(void)fatalCoreDataError:(NSNotification *)notification

    {

        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Internal Error", nil) message:NSLocalizedString(@"There was a fatal error in the app and it cannot continue. Press OK to terminate the app. Sorry for the inconvenience.", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"OK", nil) otherButtonTitles:nil];

        [alertView show];

    }

    PS:以下两步用于找出错误

    5.在AppDelegate.m文件中实现UIAlertViewDelegate

    @interface AppDelegate () <UIAlertViewDelegate>

    @end

    6.在AppDelegate.m文件中添加以下代码,当弹出的窗口消失时停止APP运行,并指出错误代码的位置

    -(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex

    {

        abort();

    }

    7.在AppDelegate.m文件顶部添加以下代码,让该对象了解以上定义的NSNotification消息

    NSString * const ManagedObjectContextSaveDidFailNotification = @"ManagedObjectContextSaveDidFailNotification";

    8.在每个需要错误处理的地方添加以下代码

            NSError *error;

            FATAL_CORE_DATA_ERROR(error);

  • 相关阅读:
    Linux 下安装 numpy 和 scipy
    排序算法总结
    机器学习&数据挖掘笔记_16(常见面试之机器学习算法思想简单梳理)
    Java读取Excel并解析文本(并格式化输出)
    快捷键记忆
    初级应该学习的
    深入理解加密、解密、数字签名和数字证书
    数据签名和验签
    POI结构与常用类
    exlipse继承反编译插件
  • 原文地址:https://www.cnblogs.com/guitarandcode/p/5572429.html
Copyright © 2011-2022 走看看