WebberLai WebberLai - 1 year ago 102
Objective-C Question

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

As the title says, what's the difference between


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

Which condition should I use ?

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


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


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

Which one is right ?

Answer Source

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

 #define nil NULL


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.


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:@""])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download