This question already has an answer here:
- How to detect if NSString is null? 5 answers
I want to check weather a NSString is null or not. Im assigning from an JSON array. After assigning that string value is <null>. Now I want to check this string is null or not. So I put like this
if (myStringAuthID==nil) but this if statement always false. How I can check a string for null. Please help me
Thanks
Like that:
[myString isEqual: [NSNull null]];
There are three possible interpretations of "null" NSString:
someStringPtr == nil(id)someStringPtr == [NSNull null]someStringPtr.length == 0
If you may have the possibility of all 3, the 3rd check subsumes the first, but I don't know of a simple check for all three.
In general, JSON will return [NSNull null] for a null JSON value, but some kits may return @"" (length == 0) instead. nil will never be used in iOS since it can't be placed in arrays/dictionaries.
Try if(myString == [NSNull null]). That should evaluate it properly.
I think that is best if you check before cast it to an NSString or whatever, you have different options, the above are correct, but I prefer this:
id NilOrValue(id aValue) {
if ((NSNull *)aValue == [NSNull null]) {
return nil;
}
else {
return aValue;
}
}
Using this snippet (pay attention that is a C function) before passing the value to a pointer you can safely pass a value or nil if the value in NSNull. Passing nil is great, because if you send a message to a nil object, it doesn't throw an exception. You can also check for class type with -isKindOfClass.
Here is part of a string category I created:
@interface NSString (Enhancements)
+(BOOL)isNullOrEmpty:(NSString *)inString;
@end
@implementation NSString (Enhancements)
+(BOOL)isNullOrEmpty:(NSString *)inString
{
BOOL retVal = YES;
if( inString != nil )
{
if( [inString isKindOfClass:[NSString class]] )
{
retVal = inString.length == 0;
}
else
{
NSLog(@"isNullOrEmpty, value not a string");
}
}
return retVal;
}
@end
来源:https://stackoverflow.com/questions/19546920/how-to-check-nsstring-is-null-or-not