Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do you check for null in Objective-C?

Nil = (capitalized) is a null pointer to an Objective-C class. NULL = (all caps) is a null pointer to anything else (C pointers, that is). [NSNull null] = (singleton) for situations where use of nil is not possible (adding/receiving nil to/from NSArrays e.g.)

How do you check if a string is empty or null in Objective-C?

You can check if [string length] == 0 . This will check if it's a valid but empty string (@"") as well as if it's nil, since calling length on nil will also return 0.

How do I check if a string contains a substring in Objective-C?

To check if a string contains another string in objective-c, we can use the rangeOfString: instance method where it returns the {NSNotFound, 0} if a 'searchString' is not found or empty (""). Output: string contains you!


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.


Refer to the following related articles on this site:

  • Is if (variable) the same as if (variable != nil) in Objective-C h

I think your error is related to something else as you shouldn't need to do the extra checking.

Also see this related question: Proper checking of nil sqlite text column


I have found that in order to really do it right you end up having to do something similar to

if ( ( ![myString isEqual:[NSNull null]] ) && ( [myString length] != 0 ) ) {
}

Otherwise you get weird situations where control will still bypass your check. I haven't come across one that makes it past the isEqual and length checks.