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

3

18

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

Pillowcase answered 4/10, 2010 at 15:32 Comment(0)
D
8

Your solution, extracting an NSArray once during viewDidLoad, is the correct one. You actually won't be duplicating much memory. Your objects will still only be in memory once; it's just that your NSSet and NSArray will both contain pointers to those objects.

Dinnage answered 4/10, 2010 at 18:38 Comment(0)
A
33

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)

Apgar answered 4/10, 2010 at 15:48 Comment(1)
This answer actually has the answer to the original question.Claret
D
8

Your solution, extracting an NSArray once during viewDidLoad, is the correct one. You actually won't be duplicating much memory. Your objects will still only be in memory once; it's just that your NSSet and NSArray will both contain pointers to those objects.

Dinnage answered 4/10, 2010 at 18:38 Comment(0)
C
3

Use NSOrderedSet instead of NSSet.

Charismatic answered 8/6, 2015 at 1:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.