Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

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

Why are these different?

like image 968
user4951 Avatar asked Nov 20 '12 07:11

user4951


2 Answers

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.

like image 157
Wade Tregaskis Avatar answered Oct 21 '22 00:10

Wade Tregaskis


While there are other differences†, .allObjects does not imply a definite ordering, and .array does; and that's exactly what you are getting.


.array returns a live proxy of the underlying NSOrderedSet, and if the underlying ordered set changes, the proxy will change with it.

like image 36
Clay Bridges Avatar answered Oct 20 '22 22:10

Clay Bridges