Search code examples
objective-cxcodeclang-static-analyzer

Getting "Array element cannot be nil" from Analyzer as a false-positive


I have a case where the XCode analyzer is flagging valid code.

We have an NSString category with a method isEmpty which checks if the string is empty, including checking for a nil string. When it's used in combination with adding the string to an array, the analyzer complains:

if (![NSString isEmpty:myString]) {
    [_myArray addObject:myString];
}

The analyzer will then complain with Array element cannot be nil, because it isn't smart enough to detect that isEmpty is preventing that.

What's the best workaround? I know I can change the condition to if (myString && ![NSString isEmpty... but that seems like a clunky workaround.

EDIT: By request, here's the body of isEmpty:

+ (BOOL)isEmpty:(NSString *)string
{
    return (string ? [string isEqualToString:@""] : YES); 
}

Solution

  • You're correct that you have to show the analyzer every possible logical path. Your "workaround" is perfectly good.

    It might be that your isEmpty could be written to help the analyzer more, but you didn't show that, so it's impossible to say. Based on what you've actually shown, I would suggest that you just use your "workaround" and move on.