how to Check NSString is null or not [duplicate]

笑着哭i 提交于 2019-11-30 04:47:15
Mirko Catalano

Like that:

[myString isEqual: [NSNull null]];

There are three possible interpretations of "null" NSString:

  1. someStringPtr == nil
  2. (id)someStringPtr == [NSNull null]
  3. 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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!