开发者

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

开发者 https://www.devze.com 2023-01-18 12:43 出处:网络
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 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 cellForRo开发者_运维知识库wAtIndexPath 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


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)


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.


Use NSOrderedSet instead of NSSet.

0

精彩评论

暂无评论...
验证码 换一张
取 消