How can I test an NSString for being nil?

前端 未结 8 1832
借酒劲吻你
借酒劲吻你 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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
    }
    

提交回复
热议问题