Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 860
Webber Lai Avatar asked Nov 26 '10 08:11

Webber Lai


People also ask

What is the difference between the Swift nil and the OBJ C nil?

In Objective-C, nil is a pointer to a non-existent object. In Swift, nil is not a pointer but the absence of a value of a certain type. Optionals of any type can be set to nil, not just object types.

What is null in Objective-C?

In Objective-C, you work with references to objects by using pointers that can be null, called nil in Objective-C. In Swift, all values — including object instances — are guaranteed to be non-null. Instead, you represent a value that could be missing as wrapped in an optional type.

Is nil and zero the same?

Nil means the same as zero. It is usually used to say what the score is in sports such as rugby or football.

Is nil the same as null Ruby?

Let's start out with “Nil” since it's the most common and easy-to-understand way of representing nothingness in Ruby. In terms of what it means, Nil is exactly the same thing as null in other languages.


2 Answers

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:@""]) 
like image 92
Vladimir Avatar answered Oct 08 '22 05:10

Vladimir


nil == (id) 0 Nil == (Class) 0 NULL == (void *) 0 

@"" is an empty NSString constant.

like image 41
NSResponder Avatar answered Oct 08 '22 06:10

NSResponder