Clang Error on “Potential null dereference.”

前端 未结 2 615
我寻月下人不归
我寻月下人不归 2021-02-01 00:51

I keep getting Clang errors on the following type of code and I can\'t figure out why they\'re erroneous or how to resolve them to Clang\'s satisfaction:

+ (NSSt         


        
相关标签:
2条回答
  • 2021-02-01 01:26

    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 = ...;
    
    0 讨论(0)
  • 2021-02-01 01:50

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题