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 ?
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.
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.
Nil means the same as zero. It is usually used to say what the score is in sports such as rugby or football.
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.
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:
-isEqualToString:
messageSo 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:@""])
nil == (id) 0 Nil == (Class) 0 NULL == (void *) 0
@"" is an empty NSString constant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With