iOS之《Effective Objective-C 2.0》读书笔记(21)

来源:互联网 发布:搜狐汽车 大数据 编辑:程序博客网 时间:2024/06/05 08:07

第21条:理解Objective-C错误模型

1.较为严重的情况:@throw 自定义异常

  • 抽象基类,只能先继承它写一个子类,然后通过子类调用方法,但是编译器不会识别它是不是抽象基类,所以需要在子类必须覆写的超类方法中抛异常,防止有人创建基类实例:
-(void)mustOverrideMethod{    NSString *reason = [NSString stringWithFormat:@"%@ must be overridden",NSStringFromSelector(_cmd)];    @throw [NSException exceptionWithName:NSInvalidArgumentException reason:reason userInfo:nil];}

2.不严重的情况:NSError

(1)委托方法

  • 例:NSURLConnection的代理
@protocol NSURLConnectionDelegate <NSObject>- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;

(2)经由“输出参数”返回给调用者

-(BOOL)doSomething:(NSError **)error{    if(error != nil){        //错误范围-domain,错误码-code,用户信息-userInfo        *error = [NSError errorWithDomain:domain code:code userInfo:userInfo];        NSLog(@"%@",*error);        return NO;    }else{        return YES;    }}
原创粉丝点击