Reputation:
I've an NSString thats populated from some data returned via JSON.
The code works great under normal circumstances but there is an occasion when i get returned by the JSON.
When i do a check to see if my NSString == nil or == null it fails the test.
But the fact that the NSString contains crashes my app.
So does have some special meaning in Objective C? Or should i just do a string compare and see if the string is equal to rather than being nil and handle it that way.
This has me a little confused.
Many Thanks, Code
Upvotes: 3
Views: 2969
Reputation: 1
I did it this way:
if([string isKindOfClass:[NSNull class]]) {
NSLog(@"This is JSON null");
} else {
NSLog(@"This is a string, do what you wanna do with it");
}
Upvotes: 0
Reputation:
You could check to see if it's null by.
if ([str isKindOfClass:[NSNull class]]) {
// str is null.
}
Upvotes: 2
Reputation: 28242
<null>
is what NSNull
returns for its -description
method. You need to also check for
myString == [NSNull null]
in this case.
Additional info: IIRC the common Objective-C JSON stuff will use [NSNull null]
for null
s in the JSON structure, to differentiate the value from one that simply isn't there.
Upvotes: 7
Reputation: 11725
NSString *
is just a pointer to a NSString
object.
To test for null pointer:
NSString *str;
if (str) {
// str points to an object
if ([str length] == 0) {
// string is empty
}
} else
// str points to nothing
}
If you want to check for whitespace, you can trim the NSString with stringByTrimmingCharactersInSet
.
Upvotes: 2