How can I test an NSString for being nil?

前端 未结 8 1817
借酒劲吻你
借酒劲吻你 2020-12-09 07:12

Can I simply use

if(myString == nil)

For some reason a string that I know is null, is failing this statement.

相关标签:
8条回答
  • 2020-12-09 07:43

    You can implicitly check for nil (allocated, but not initialized) with this:

    if (!myString) { 
        //do something
    }
    

    If myString was assigned from a dictionary or array, you may also wish to check for NSNULL like this:

    if ([myString isEqual:[NSNull null]]) {
        //do something
    }
    

    Finally (as Sophie Alpert mentioned), you can check for empty strings (an empty value):

    if ([myString length] == 0) {
        //do something
    }
    

    Often, you may want to consolidate the expressions:

    if (!myString || [myString length] == 0) {
        //do something
    }
    
    0 讨论(0)
  • 2020-12-09 07:53

    Notice length = 0 doesn't necessary mean it's nil

    NSString *test1 = @"";
    NSString *test2 = nil;
    

    They are not the same. Although both the length are 0.

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