valueForKey:
(and most other Cocoa methods) returns a pointer (memory address) to an object. When you use the ==
symbol you're simply test the numeric value of that pointer and not the actual value of the string. When you use isEqualToString:
, you are testing the value.
These two:
if ([dictionary valueForKey:@"aString"]==nil)
if ([dictionary valueForKey:@"aString"]==NULL)
are more-or-less equivalent and both test "Was the address returned equal to zero?", which is how valueForKey:
indicates there was no object found for that key. If the dictionary does contain any object for that key, regardless of its value (e.g. Even an empty string) this if statement returns false.
(You normally use the nil
version in Objective-C, as a styling convention as much as anything else)
This:
if ([[dictionary valueForKey:@"aString"] isEqualToString:@""])
Tests the actual value of the string to see if it's a zero length string. If there is no object in the dictionary, it will return false, since when you call isEqualToString:
(or almost any other method) against a nil
pointer you always get zero, or false.