WebberLai WebberLai - 3 months ago 9
Objective-C Question

Objective-C: What's the difference between NULL, nil and @""?

As the title says, what's the difference between

NULL
,
nil
and
@""
?

For example, if I want to check a string in a dictionary is empty.

Which condition should I use ?

if ([dictionary objectForKey:@"aString"] == nil)


or

if [[dictionary objectForKey:@"aString"] isEqualToString:@""]


or

if ([dictionary objectForKey:@"aString"] == NULL)


Which one is right ?

Answer

nil is NULL's analog for objective-c objects. Actually they're the same:

 //MacTypes.h
 #define nil NULL

So

if ([dictionary valueForKey:@"aString"]==nil)
if ([dictionary valueForKey:@"aString"]==NULL)

both check if the specific key is present in a dictionary, although 1st line is more correct as it checks objective-c types.

About:

if ([[dictionary valueForKey:@"aString"] isEqualToString:@""])

This line checks if there's an entry in dictionary with "aString" key and compares that entry with empty string. The result will be one of the following:

  • is false if there's no such entry for your key
  • is true if there's entry for your key and that entry is empty string
  • may crash if object for your key exists and does not respond to -isEqualToString: message

So depending on your needs you must use 1st line, or if you need to combine both checking if entry exists and it is not an empty string then you need 2 conditions:

if ([dictionary valueForKey:@"aString"]==nil ||
               [[dictionary valueForKey:@"aString"] isEqualToString:@""])