Does using a string literal like @"key"
in setObject(id):forKey(id)
only work because the compiler optimizes all instances of the string literal to point to the same object? Or does retrieving an object with objectForKey(id)
actually compare the string value of the key?
What if the NSDictionary
was created by an external function like JSON parsing? Now when I access the objects using string literals for keys, it would be the first time the compiler sees the key strings and it would not be the same object used by the JSON parser when it created the dictionary.
Should I use valueForKey(NSString *)
instead when accessing values from an externally created dictionary?
NSDictionary is a hash table, which means that at first some function is calculated over the key to find the index of value in some array (called hash code, it is a quick operation). Then, since some keys can produce the same hash value, all keys for this hash code are compared to the one we are searching for.