Array from set: why does NSSet use allObjects, while NSOrderedSet uses array?

user4951 picture user4951 · Nov 20, 2012 · Viewed 8.9k times · Source

In Foundation, if I want to convert a set to an NSArray, I can use:

  • -[NSSet allObjects]
  • -[NSOrderedSet array]

Why are these different?

Answer

Wade Tregaskis picture Wade Tregaskis · Nov 20, 2012

Speculation, but:

Because when NSSet was created the only other major collection type was NSArray, which was (and still is, largely) the most common collection type. So a method called "allObjects" would obviously return an NSArray.

When NSOrderedSet was added much more recently, it had to deal with the existence of prior collections - primarily, NSArray and NSSet. So an "allObjects" method would be ambiguous. Ergo it has two methods, -array and -set.

And/or, the -array and -set methods return proxies to what are likely the same or similar classes used internally. So in a functional sense they're a little different - those proxies will see mutations made on the original NSOrderedSet. -allObjects on the other hand does not - it genuinely creates an independent array, since its internal storage is likely a hashtable or similar that isn't readily proxied.