How can I test an NSString for being nil?

2019-01-17 18:37发布

Can I simply use

if(myString == nil)

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

8条回答
冷血范
2楼-- · 2019-01-17 19:13

you may check your getting string using this

   if(myString==(id) [NSNull null] || [myString length]==0 || [myString isEqualToString:@""])
    {
     //String is null or bad response
    }
查看更多
Luminary・发光体
3楼-- · 2019-01-17 19:17

Is it possible that your string is not in fact nil, and is instead just an empty string? You could try testing whether [myString length] == 0.

查看更多
成全新的幸福
4楼-- · 2019-01-17 19:19

I encountered this problem today. Despite assigning a string to be nil: NSString *str = nil;, the test if (str == nil) returned FALSE! Changing the test to if (!str) worked, however.

查看更多
ゆ 、 Hurt°
5楼-- · 2019-01-17 19:23

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
}
查看更多
▲ chillily
6楼-- · 2019-01-17 19:25

You can find more on objective C string here.

+ (BOOL ) stringIsEmpty:(NSString *) aString {

    if ((NSNull *) aString == [NSNull null]) {
        return YES;
    }

    if (aString == nil) {
        return YES;
    } else if ([aString length] == 0) {
        return YES;
    } else {
        aString = [aString stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
        if ([aString length] == 0) {
            return YES;
        }
    }

    return NO;  
}

+ (BOOL ) stringIsEmpty:(NSString *) aString shouldCleanWhiteSpace:(BOOL)cleanWhileSpace {

    if ((NSNull *) aString == [NSNull null]) {
        return YES;
    }

    if (aString == nil) {
        return YES;
    } else if ([aString length] == 0) {
        return YES;
    } 

    if (cleanWhileSpace) {
        aString = [aString stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
        if ([aString length] == 0) {
            return YES;
        }
    }

    return NO;  
}
查看更多
一纸荒年 Trace。
7楼-- · 2019-01-17 19:27

It seems that my string in the debugger was reporting as (null) but that was due to how it was being assigned, I fixed it and now it is reporting as nil. This fixed my issue.

Thanks!

查看更多
登录 后发表回答