Reputation: 270
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);
}
Upvotes: 1
Views: 346
Reputation: 285240
In Objective-C the easiest way to check for non-nil
and non-empty
for NSString
is to get the length
. It returns 0 for nil
and empty
and the proper length for non-empty
.
NSString *testNil = nil;
NSString *testEmpty = @"";
NSString *testNonEmpty = @"Hello";
NSInteger testNilLength = [testNil length]; // -> 0
NSInteger testEmptyLength = [testEmpty length]; // -> 0
NSInteger testNonEmptyLength = [testNonEmpty length]; // -> 5
Upvotes: 1
Reputation: 535925
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.
Upvotes: 1