使用ARC处理NSError - 泄漏

时间:2012-03-11 16:33:48

标签: iphone objective-c ios ipad automatic-ref-counting

- (BOOL)parserJSONString:(NSString *)jsonString error:(NSError **)anError {
   //some data getting
   //error handle

    NSString *description = @"phone number couldn't be using";
    NSString *recoverySuggestion = @"Please provide an other phone number.";
    NSInteger errorCode = -1;
    NSArray *keys = [NSArray arrayWithObjects: NSLocalizedDescriptionKey, NSLocalizedRecoverySuggestionErrorKey, nil];
    NSArray *values = [NSArray arrayWithObjects:description, recoverySuggestion, nil];
    NSDictionary *userDict = [NSDictionary dictionaryWithObjects:values forKeys:keys];
    *anError = [[NSError alloc] initWithDomain:@"my domain" code:errorCode userInfo:userDict];
    return NO;
}

*anError = [[NSError alloc] initWithDomain:@"my domain" code:errorCode userInfo:userDict];编译器给出下一个泄漏警告 “潜在的空取消引用。根据'创建和返回NSError对象'中的编码标准,参数''可能为空”
如何解决这个问题?

2 个答案:

答案 0 :(得分:14)

您需要先检查anErrornil还是NULL

if (anError) {
    *anError = [[NSError alloc] initWithDomain:@"my domain" code:errorCode userInfo:userDict];
}

答案 1 :(得分:6)

这实际上不是泄漏警告,而是空指针的潜在解引用。编译器抱怨行

*anError = [[NSError alloc] initWithDomain:@"my domain" code:errorCode userInfo:userDict];

您指定anError指向的位置而不检查anError实际上是否为空指针(根据编码标准允许“),如果调用者可能会发生对详细的错误信息不感兴趣。)