使用ARC处理NSError - 泄漏

row*_*man 1 iphone objective-c ipad ios 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;
}
Run Code Online (Sandbox Code Playgroud)

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

Dar*_*ust 14

您需要先检查是否anError:nilNULL:

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


Dir*_*irk 6

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

*anError = [[NSError alloc] initWithDomain:@"my domain" code:errorCode userInfo:userDict];
Run Code Online (Sandbox Code Playgroud)

anError无需检查就指定了所指向的位置,是否anError实际上是空指针(根据编码标准允许",如果调用者对详细错误信息不感兴趣,则可能发生).