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

Teo Choong Ping picture Teo Choong Ping · Jun 9, 2009 · Viewed 178.8k times · Source

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?

Answer

Peter N Lewis picture Peter N Lewis · Jun 10, 2009

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.