What is the right way to check for a null string in Objective-C?

Viewed 188786

I was using this in my iPhone app

if (title == nil) {
    // do something
}

but it throws some exception, and the console shows that the title is "(null)".

So I'm using this now:

if (title == nil || [title isKindOfClass:[NSNull class]]) {
    //do something
}

What is the difference, and what is the best way to determine whether a string is null?

20 Answers

As others have pointed out, there are many kinds of "null" under Cocoa/Objective C. But one further thing to note is that [title isKindOfClass:[NSNull class]] is pointlessly complex since [NSNull null] is documented to be a singleton so you can just check for pointer equality. See Topics for Cocoa: Using Null.

So a good test might be:

if (title == (id)[NSNull null] || title.length == 0 ) title = @"Something";

Note how you can use the fact that even if title is nil, title.length will return 0/nil/false, ie 0 in this case, so you do not have to special case it. This is something that people who are new to Objective C have trouble getting used to, especially coming form other languages where messages/method calls to nil crash.

it is just as simple as

if([object length] >0)
{
  // do something
}

remember that in objective C if object is null it returns 0 as the value.

This will get you both a null string and a 0 length string.

If you want to test against all nil/empty objects (like empty strings or empty arrays/sets) you can use the following:

static inline BOOL IsEmpty(id object) {
    return object == nil
        || ([object respondsToSelector:@selector(length)]
        && [(NSData *) object length] == 0)
        || ([object respondsToSelector:@selector(count)]
        && [(NSArray *) object count] == 0);
}

MACRO Solution (2020)

Here is the macro that I use for safe string instead of getting "(null)" string on a UILabel for example:

#define SafeString(STRING) ([STRING length] == 0 ? @"" : STRING)

let say you have an member class and name property, and name is nil:

NSLog(@"%@", member.name); // prints (null) on UILabel

with macro:

NSLog(@"%@", SafeString(member.name)); // prints empty string on UILabel

nice and clean

Extension Solution (2020)

If you prefer checking nil Null and empty string in your project you can use my extension line below:

NSString+Extension.h

///
/// Checks if giving String is an empty string or a nil object or a Null.
/// @param string string value to check.
///
+ (BOOL)isNullOrEmpty:(NSString*)string;

NSString+Extension.m

+ (BOOL)isNullOrEmpty:(NSString*)string {
    if (string) { // is not Nil
        NSRange range = [string rangeOfString:string];
        BOOL isEmpty = (range.length <= 0 || [string isEqualToString:@" "]);
        BOOL isNull = string == (id)[NSNull null];

        return (isNull || isEmpty);
    }

    return YES;
}

Example Usage

if (![NSString isNullOrEmpty:someTitle]) {
    // You can safely use on a Label or even add in an Array for example. Remember: Arrays don't like the nil values!
}

If that kind of thing does not already exist, you can make an NSString category:

@interface NSString (TrucBiduleChoseAdditions)

- (BOOL)isEmpty;

@end

@implementation NSString (TrucBiduleChoseAdditions)

- (BOOL)isEmpty {
    return self == nil || [@"" isEqualToString:self];
}

@end

What works for me is if ( !myobject )

if ([linkedStr isEqual:(id)[NSNull null]])
                {
                    _linkedinLbl.text=@"No";
                }else{
                    _linkedinLbl.text=@"Yes";
                }

For string:

+ (BOOL) checkStringIsNotEmpty:(NSString*)string {
if (string == nil || string.length == 0) return NO;
return YES;

}

Refer the picture below:

enter image description here

For string:

+ (BOOL) checkStringIsNotEmpty:(NSString*)string {
if (string == nil || string.length == 0) return NO;
return YES;}
Related