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);

  • 相关阅读:
    HDU 1025 Constructing Roads In JGShining's Kingdom (DP+二分)
    HDU 1158 Employment Planning
    HDU 2059 龟兔赛跑
    Csharp 简单操作Word模板文件
    Csharp windowform datagridview Clipboard TO EXCEL OR FROM EXCEL DATA 保存datagridview所有數據
    Csharp 讀寫文件內容搜索自動彈出 AutoCompleteMode
    Csharp windowform controls clear
    CSS DIV大图片右上角叠加小图片
    Csharp DataGridView自定义添加DateTimePicker控件日期列
    Csharp 打印Word文件默認打印機或選擇打印機設置代碼
  • 原文地址:https://www.cnblogs.com/guitarandcode/p/5572429.html
Copyright © 2011-2022 走看看