Reputation: 33138
In Foundation, if I want to convert a set to an NSArray
, I can use:
-[NSSet allObjects]
-[NSOrderedSet array]
Why are these different?
Upvotes: 21
Views: 9354
Reputation: 11890
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.
Upvotes: 6
Reputation: 111
Also... The NSArray returned by 'allObjects' is a copy of the values in the set.
But the NSArray returned by 'array' is a proxy of the objects in the set.
Thus if you change the value of any object in the set, you will change the value of the object in the array. A copy of the ordered set is not being made. So the two properties have different names because they do different things.
Upvotes: 1
Reputation: 2018
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.
Upvotes: 21