Clang Error on “Potential null dereference.”

回眸只為那壹抹淺笑 提交于 2019-12-02 17:51:33
Daniel Martin

The way to do what's expected is shown in listing 3-5 in that document. With your example code:

+ (NSString *)checkForLength: (NSString *)theString error: (NSError **)error {
    BOOL hasLength = ([theString length] > 0);
    if (hasLength) return theString;
    else {
        if (error != NULL) *error = [NSError errorWithDomain:@"ErrorDomain" code:hasLength userInfo:nil];
        return nil;
    }
}

The Cocoa convention is that the return value should indicate success or failure (in this case, you return nil for failure) and the error is filled in with additional information, but only when the caller requests it.

In other words

NSError *error = nil;
NSString *result = [self checkForLength: aString error: &error];

and

NSString *result = [self checkForLength: aString error: NULL];

are both valid ways to invoke the method. So the method body should always check for a NULL error param:

if (error != NULL)
    *error = ...;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!