I have the following code:
NSString *content = [[NSUserDefaults standardUserDefaults] stringForKey:@"mykey"];
NSLog(@"string is %@",content);
if ([content stringIsEmpty]){
NSLog(@"empty string");
}else{
NSLog(@"string is not empty");
}
stringIsEmpty is class category on NSString:
- (BOOL ) stringIsEmpty {
if ((NSNull *) self == [NSNull null]) {
return YES;
}
if (self == nil) {
return YES;
} else if ([self length] == 0) {
return YES;
}
return NO;
}
The output is:
string is (null)
string is not empty
How could it be null and not empty at the same time?
What happens is that:
[content stringIsEmpty:YES]will return false (
NO), whencontentisnil. So your code will take thebranch. This would be better:
A better way of doing this would be reversing the semantics of the method:
this would work finely because when
contentisnilit would returnNO, when it is notnil, it would execute your method.EDIT:
In Objective-C, sending a message to
nilis legal and by definition will evaluate tonil. Google for “objective c sending message to nil”.In another language (C++), your code would crash (actually undefined behaviour, but to make things simple).