How can I test an NSString for being nil?

2019-01-17 18:49发布

问题:

Can I simply use

if(myString == nil)

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

回答1:

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.



回答2:

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;  
}


回答3:

you may check your getting string using this

   if(myString==(id) [NSNull null] || [myString length]==0 || [myString isEqualToString:@""])
    {
     //String is null or bad response
    }


回答4:

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!



回答5:

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.



回答6:

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
}


回答7:

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.



回答8:

Check NSAttributedString is empty:

let isEmpty = atrributedString.string.isEmpty