简体   繁体   English

每次都会[NSSet allObjects]返回一个具有相同顺序的数组吗?

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

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. 我有一个从.NET WebService返回的自定义对象列表,并使用父级enitity与Core Data的To-Many关系存储它们。

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. 我想使用NSSet作为UITableView的数据源,并在选择行时将新控制器压入堆栈。

When using [NSSet allObjects] does the array returned always have the same order? 使用[NSSet allObjects]返回的数组是否总是具有相同的顺序? (I guess not as sets are unordered) (我猜不是因为集合是无序的)

If not, how then can I use NSArray *myArray = [mySet allObjects]; 如果没有,我怎么能使用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? cellForRowAtIndexPath中获取单元格的textLabel的名称,然后再在didSelectRowAtIndexPath中将对象分配给即将推送的ViewController?

I already have the parent object synthesized in my UITableViewDelegate . 我已经在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 我还想过在viewDidLoad合成并使用allObjects只创建一次NSArray但是这会复制内存中的数据

There's no guarantee that they'll be in the same order, since an NSSet does not (technically) maintain order. 由于NSSet没有(技术上)维持秩序,因此无法保证它们的顺序相同。 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. -[NSSet allObjects]返回)[a]包含集合成员的数组,如果集合没有成员则返回一个空数组。 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. 您的解决方案,在viewDidLoad期间提取一次NSArray是正确的。 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. 只是你的NSSetNSArray都包含指向这些对象的指针。

使用NSOrderedSet而不是NSSet。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM