zoukankan      html  css  js  c++  java
  • iOS异常采用处理方式

    iOS开发过程中我们经常会遇到异常问题

     

    对异常的处理一般采用打印或者直接抛出。这样可以很方便我们调试过程有所参考,而且方便我们查看异常产生的位置信息

    NSError(错误信息)

    采用NSError的情况

    使用 NSError 的形式可以把程序中导致错误原因回报给调用者,而且使程序正常运行不会造成奔溃的后果

    NSError包含的内容

    @interface NSError : NSObject <NSCopying, NSSecureCoding> {
        @private
        void *_reserved;
        NSInteger _code;
        NSString *_domain;
        NSDictionary *_userInfo;
    }
    

      

    • NSError _code(错误码, 类型 NSInteger) : 独有的错误代码,指明在某个范围内具体发生的错误。可能是一系列的错误的集合,所以可以使用 Enum 来定义。
    • NSError *_domain (错误范围,类型 NSString) :错误发生范围,通常使用一个特有的全局变量来定义。
    • NSError *_userInfo (用户信息,类型 NSDictionary) :有关错误的额外信息,其中包含一段“本地化的描述”,还可能包含导致此错误发生的另一个错误。userInfo 可以描述为一条错误的链条

    NSError使用的两种情况

    在方法实现或者是 API 设计时,我们对 NSError 的使用情形有两种:在协议中传递和“输出参数”返回给调用者

    1.通过委托协议来传递错误

    - (void)connection:(NSURLConnection *)connection withError:(NSError *)error;
    

    通过代理协议的方式可以把错误报告信息传递

    2.“输出参数”返回给调用者

    - (BOOL)doSomething:(NSError **)error;
    

    错误的信息作为一个指向指针的指针(也就是说一个指针指向错误的对象)

    @throw NSException (异常抛出)

    采用 @throw 情况

    在 APP 运行期间遇到问题,需要对问题进行操作终止程序抛出异常,可以使用 @throw 来进行

    采用 @throw 可能产生问题

    在异常抛出实例中,如果抛出异常。在实现抛出异常的代码后面的执行释放资源就不会执行,这样末尾的对象就不会被释放。如果想要生成“异常安全”的代码,可以设置编译器的标志 -fobjc-arc-exceptions 来进行实现。不过将要一如加一些额外的代码,在不抛出异常时也会执行代码。
    在不使用 ARC 时也很难实现异常抛出情况下对内存进行释放。

    NSError * error = nil;
    BOOL success = [self doSomething:&error];
    if(error && success) {
         @throw[NSException …];
    }
    [success release];
    

      

    按照上面实现当在异常抛出的过程时,success 还来不及释放。所以要解决上面的问题可以在异常抛出之前对 success 进行释放,但是当需要释放的资源有很多的情况下,这样操作起来就比较复杂。

    在开发过程中异常抛出可以使用在 抽象的基类 实例方法中进行调用。如果基类中的方法不被 override 就设置抛出异常,这样可以保证实例方法被重写。

    @try @catch @finally (异常捕捉)

    采用 @try @catch @finally 情况

    个人感觉 @try @catch @finally 是 @throw NSException 的加强版。前者可以实现对异常的捕捉,相关异常的输出,和异常输出后执行的 @finally 相关的具体操作。后者是对具体整理 NSExpection 抛出,并没有前者比较完善的流程化操作步骤。

    如果在基类中实现 @throw 进行设置 必须 override 基类中的实例方法,那么捕获异常的方法中使用 @try @catch @finally。例如:NSArray,NSDictionary 初始变量使用字面量来获取值时,需要判断返回数据是否为 nil 来防止 APP Crash。

    产生问题和解决方式

    当使用 @try @catch @finally 时,有两种情况 MRCARC

    MRC(iOS 5 之前) 的环境中,上面的代码可以展示为:

    SomeClass *someClass = nil;
    @try {
           someClass = [[SomeClass alloc] init];
           [someClass doSomeThingsThatMayThrow];
    }
    @catch() {
         NSLog(… …);
    }
    @finally {
         [someClass release];
    }
    

      

    在 ARC 的环境中,上面的代码展示为:

    SomeClass *someClass = nil;
    @try {
           someClass = [[SomeClass alloc] init];
           [someClass doSomeThingsThatMayThrow];
    }
    @catch( … ) {
         NSLog(… …);
    }
    @finally {
        
    }
    

      

    可以看出在 MRC 的情形下可以实现对于内存的释放,在 ARC 的情形下会系统会实现对内存的释放? 这样向正确吗?

    答案是:ARC 不会自动处理,因为如果要实现自动处理可能要加入大量的代码,才可以清楚对象实现抛出异常时将其清理。但是如果加入代码就会影响运行时的性能,在正常运行时也会如此。
    如果在当前实现中开启 -fobjc-arc-exception 的模式可以实现在 @try @catch @finally 在异常情况下实现对未释放的对象进行内存的释放管理

    @try@catch@finally 的 C++ 源码

    查看异常抛出的源码:
    建立项目在 main.m 文件中实现下面代码:

    SomeClass *someClass = nil;
    @try {
           someClass = [[SomeClass alloc] init];
           [someClass doSomeThingsThatMayThrow];
    }
    @catch( … ) {
         NSLog(… …);
    }
    @finally {
        
    }
    

      

    打开终端在 main.m 终端的文件夹路径执行下面的语句

    clang -x objective-c -rewrite-objc -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk main.m
    

    会生成文件 main.cpp 的文件,可以打开查看文 @try @catch @fianlly

    NSExpection 属性内容
    __attribute__((__objc_exception__))
    
    #ifndef _REWRITER_typedef_NSException
    #define _REWRITER_typedef_NSException
    typedef struct objc_object NSException;
    typedef struct {} _objc_exc_NSException;
    #endif
    
    struct NSException_IMPL {
        struct NSObject_IMPL NSObject_IVARS; //实例变量
        NSString *name;                      //exception 的名字
        NSString *reason;                    //exception 产生的原因
        NSDictionary *userInfo;              //exception 展示使用详细的信息
        id reserved;                         //
    };
    

      

    NSError 属性内容
    #ifndef _REWRITER_typedef_NSError
    #define _REWRITER_typedef_NSError
    typedef struct objc_object NSError;
    typedef struct {} _objc_exc_NSError;
    #endif
    
    struct NSError_IMPL {
        struct NSObject_IMPL NSObject_IVARS; //实例变量
        void *_reserved;                     //实例调用的方法
        NSInteger _code;                     //error 错误码
        NSString *_domain;                   //error 错误发生范围
        NSDictionary *_userInfo;             //error 错误描述的具体信息
    };
    

      

    下面在 main.m 中使用 Clang 解析 @try @catch @finally 在 C++ 环境中解析

     

    在没有参数的情况下

    int main() {
        
        @try {
            
        } @catch (NSException *exception) {
            
        } @finally {
            
        }
    }
    

      

    经过 Clang 解析后源码如下:

    int main() {
    
    { id volatile _rethrow = 0;
        try {
            try {
                     //异常捕获
                } catch (_objc_exc_NSException *_exception) {
                     NSException *exception = (NSException*)_exception; 
                     //捕获异常,并进行抛出
                } 
            }
        catch (id e) {
             _rethrow = e;
            }
        {  
          struct _FIN { _FIN(id reth) : rethrow(reth) {}
            ~_FIN() { if (rethrow) objc_exception_throw(rethrow); }
            id rethrow;
            } _fin_force_rethow(_rethrow);
               //异常抛出后执行的 finally 的内容
            }
        }
    }
    static struct IMAGE_INFO { unsigned version; unsigned flag; } _OBJC_IMAGE_INFO = { 0, 2 };
    

      

    在有参数的情况下

    int main() {
        
        NSDictionary *dic = @{@"name":@"liang",
                              @"last name":@"bai",
                              @"dream":@"to be a bussinessman",
                              @"work":@"IT"};
        
        NSString *salaryLiterals = nil;
        NSString *salaryAtIndex = nil;
        @try {
            
            salaryAtIndex = [dic objectForKey:@"salary"];
            salaryLiterals = dic[@"salary"];
            
        } @catch (NSException *exception) {
            NSLog(@"error name is %@, reason : %@, userInfo : %@", exception.name, exception.reason, exception.userInfo);
        } @finally {
            
        }
    }
    

      

    经过 Clang 解析后源码如下:

    int main() {
        NSDictionary *dic = ((NSDictionary *(*)(Class, SEL, const ObjectType *, const id *, NSUInteger))(void *)objc_msgSend)(objc_getClass("NSDictionary"), 
    sel_registerName("dictionaryWithObjects:forKeys:count:"), 
    (const id *)__NSContainer_literal(4U, (NSString *)&__NSConstantStringImpl__var_folders_tv_4c43vcqx24vcxx6d51n4ntc00000gn_T_main_753a25_mi_1,
    (NSString *)&__NSConstantStringImpl__var_folders_tv_4c43vcqx24vcxx6d51n4ntc00000gn_T_main_753a25_mi_3, 
    (NSString *)&__NSConstantStringImpl__var_folders_tv_4c43vcqx24vcxx6d51n4ntc00000gn_T_main_753a25_mi_5, 
    (NSString *)&__NSConstantStringImpl__var_folders_tv_4c43vcqx24vcxx6d51n4ntc00000gn_T_main_753a25_mi_7).arr,
    (const id *)__NSContainer_literal(4U, (NSString *)&__NSConstantStringImpl__var_folders_tv_4c43vcqx24vcxx6d51n4ntc00000gn_T_main_753a25_mi_0, 
    (NSString *)&__NSConstantStringImpl__var_folders_tv_4c43vcqx24vcxx6d51n4ntc00000gn_T_main_753a25_mi_2,
    (NSString *)&__NSConstantStringImpl__var_folders_tv_4c43vcqx24vcxx6d51n4ntc00000gn_T_main_753a25_mi_4,
    (NSString *)&__NSConstantStringImpl__var_folders_tv_4c43vcqx24vcxx6d51n4ntc00000gn_T_main_753a25_mi_6).arr, 4U);
        NSString *salary = __null;
        { id volatile _rethrow = 0; //使用 volatile 修饰的 _rethrow 记录异常的局部变量 
            try {
                try {
                        salary = ((id  _Nullable (*)(id, SEL, KeyType))(void *)objc_msgSend)((id)dic, sel_registerName("objectForKeyedSubscript:"), 
                  (id)(NSString *)&__NSConstantStringImpl__var_folders_tv_4c43vcqx24vcxx6d51n4ntc00000gn_T_main_753a25_mi_8);
                    } 
                catch (_objc_exc_NSException *_exception) {
                 NSException *exception = (NSException*)_exception; 
                 NSLog((NSString *)&__NSConstantStringImpl__var_folders_tv_4c43vcqx24vcxx6d51n4ntc00000gn_T_main_753a25_mi_9,
                        ((NSExceptionName (*)(id, SEL))(void *)objc_msgSend)((id)exception, sel_registerName("name")), 
                        ((NSString * _Nullable (*)(id, SEL))(void *)objc_msgSend)((id)exception, sel_registerName("reason")), 
                        ((NSDictionary * _Nullable (*)(id, SEL))(void *)objc_msgSend)((id)exception, sel_registerName("userInfo")));
                } 
            }
            catch (id e) {
                _rethrow = e;
            }
             { 
                 struct _FIN { 
                    _FIN(id reth) : rethrow(reth) {}
                    ~_FIN() { 
                      if (rethrow) objc_exception_throw(rethrow); 
                    }
                    id rethrow;
                 } 
                 _fin_force_rethow(_rethrow);
                    salary = __null;
             }
        }
    }
    static struct IMAGE_INFO { unsigned version; unsigned flag; } _OBJC_IMAGE_INFO = { 0, 2 };
    

      

    总结:

    (1)遇到奔溃问题或者是错误问题,优先使用 NSError 来对奔溃和错误进行封装,然后使用 NSLog 对其进行打印

    (2)@try @catch @finally 在使用的过程中很方便,但是 MRC 中如果变量较多可能会漏掉局部变量内存释放问题和 ARC 中如果抛出问题,不会自动对局部变量释放(开启 -fobjc-arc-expections 模式会进行释放,但是引入代码对性能有所影响)



  • 相关阅读:
    IE7下总提示" 缺少标识符、字符串或数字"
    #pragma 用法
    破解win7开机密码
    教你怎么样设计一块好的PCB板精华教程
    Object reference not set to an instance of an object. 'Infinity' is not a valid value for property 'width'.
    验证时出错,HRESULT = '8000000A'
    WIN7打补丁后VS2012出现版本不兼容
    VS的快捷键
    WPF学习记录1:ListView的一个模板
    使用Xposed Installer实现Android Hook
  • 原文地址:https://www.cnblogs.com/jukaiit/p/12104661.html
Copyright © 2011-2022 走看看