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

  • 相关阅读:
    构造函数作为友元函数的参数
    引用调用
    分块查找
    折半查找
    c++中map按key和value排序
    STL之map学习实例
    STL之stack
    STL之map
    STL之string
    STL之template类模板
  • 原文地址:https://www.cnblogs.com/guitarandcode/p/5572429.html
Copyright © 2020-2023  润新知