1

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?

Monstieur
  • 7,992
  • 10
  • 51
  • 77
  • Note: The compiler does **not** optimize all instances of the same string literal to point to the same object. At one time that was true is is generally still true but there are instances where it is not true. That is why it is always necessary to use `isEqualToString` or `isEqual` and never '==' for equality comparison. – zaph Jun 12 '15 at 14:18

1 Answers1

2

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.

Nickolay Olshevsky
  • 13,706
  • 1
  • 34
  • 48
  • This does not answer the question. The question is whether string keys are treated differently from non-string key objects. Normally only the exact same key object matches the value. – Monstieur Jun 12 '15 at 13:49
  • 1
    @Locutus I disagree on both counts. It precisely answers the question and a dictionary key match does not require the exact same object to hit. – Droppy Jun 12 '15 at 13:52
  • Every NSObject has hash function, which calculates this hash value. If it is the same for some objects then equals (isEqual?) is called. – Nickolay Olshevsky Jun 12 '15 at 13:53
  • So strings are special? It should be impossible for two different non-string objects to match the same key? – Monstieur Jun 12 '15 at 13:53
  • @Locutus How many hash tables implement a scheme where key collisions are not possible? – Droppy Jun 12 '15 at 13:56
  • Strings are not special - NSDictionary talks to all key objects via hash: and isEqual: selectors (and copyWithZone: as well). – Nickolay Olshevsky Jun 12 '15 at 13:58
  • If you want to know more details about the NSDictionary internals, you can check this link: http://ciechanowski.me/blog/2014/04/08/exposing-nsdictionary/ – Nickolay Olshevsky Jun 12 '15 at 14:03
  • Within a dictionary, the keys are unique. That is, no two keys in a single dictionary are equal (as determined by isEqual:). – zaph Jun 12 '15 at 14:16