Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test an NSString for being nil?

Can I simply use

if(myString == nil)

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

like image 371
Kyle Hayes Avatar asked Nov 26 '22 20:11

Kyle Hayes


2 Answers

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.

like image 165
Sophie Alpert Avatar answered Dec 15 '22 15:12

Sophie Alpert


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;  
}
like image 36
karim Avatar answered Dec 15 '22 15:12

karim