Will [NSSet allObjects] return an array with the same order each time?

mizzle picture mizzle · Oct 4, 2010 · Viewed 16k times · Source

I have a list of custom objects being returned from a .NET WebService and am storing them using a To-Many relationship from the parent enitity with Core Data.

I want to use the NSSet as the datasource for a UITableView and push a new controller onto the stack when a row is selected.

When using [NSSet allObjects] does the array returned always have the same order? (I guess not as sets are unordered)

If not, how then can I use NSArray *myArray = [mySet allObjects]; in cellForRowAtIndexPath to get the name for the textLabel of the cell and then again in didSelectRowAtIndexPath to assign the object to the ViewController about to be pushed?

I already have the parent object synthesized in my UITableViewDelegate. I have thought about also having an NSArray synthesized and using allObjects only once in viewDidLoad to create but this is duplicating the data in memory

Answer

Dave DeLong picture Dave DeLong · Oct 4, 2010

There's no guarantee that they'll be in the same order, since an NSSet does not (technically) maintain order. If it so happens that the objects do come back in the same order each time, then be aware that that's an implementation detail, is not documented, and could potentially be changed in a future release of the frameworks.

To quote the documentation:

(-[NSSet allObjects] returns) [a]n array containing the set’s members, or an empty array if the set has no members. The order of the objects in the array isn’t defined.

(emphasis added)