What is the right way to check for a null string in Objective-C?

后端 未结 20 1685
梦毁少年i
梦毁少年i 2020-11-27 09:26

I was using this in my iPhone app

if (title == nil) {
    // do something
}

but it throws some exception, and the console shows that the ti

相关标签:
20条回答
  • 2020-11-27 10:03

    You just check for nil

    if(data[@"Bonds"]==nil){
      NSLog(@"it is nil");
    }
    

    or

    if ([data[@"Bonds"] isKindOfClass:[NSNull class]]) {
        NSLog(@"it is null");
    }
    
    0 讨论(0)
  • 2020-11-27 10:04

    As others have pointed out, there are many kinds of "null" under Cocoa/Objective C. But one further thing to note is that [title isKindOfClass:[NSNull class]] is pointlessly complex since [NSNull null] is documented to be a singleton so you can just check for pointer equality. See Topics for Cocoa: Using Null.

    So a good test might be:

    if (title == (id)[NSNull null] || title.length == 0 ) title = @"Something";
    

    Note how you can use the fact that even if title is nil, title.length will return 0/nil/false, ie 0 in this case, so you do not have to special case it. This is something that people who are new to Objective C have trouble getting used to, especially coming form other languages where messages/method calls to nil crash.

    0 讨论(0)
  • 2020-11-27 10:04

    I have found that in order to really do it right you end up having to do something similar to

    if ( ( ![myString isEqual:[NSNull null]] ) && ( [myString length] != 0 ) ) {
    }
    

    Otherwise you get weird situations where control will still bypass your check. I haven't come across one that makes it past the isEqual and length checks.

    0 讨论(0)
  • 2020-11-27 10:04

    For string:

    + (BOOL) checkStringIsNotEmpty:(NSString*)string {
    if (string == nil || string.length == 0) return NO;
    return YES;}
    
    0 讨论(0)
  • 2020-11-27 10:09

    What works for me is if ( !myobject )

    0 讨论(0)
  • 2020-11-27 10:10

    it is just as simple as

    if([object length] >0)
    {
      // do something
    }
    

    remember that in objective C if object is null it returns 0 as the value.

    This will get you both a null string and a 0 length string.

    0 讨论(0)
提交回复
热议问题