NSMutableSet intput is not in the same order as output [closed]

只愿长相守 提交于 2019-12-12 00:43:47

问题


I have added objects into a NSMutableSet with this code:

_theQuestionsSet = [[NSMutableSet alloc]initWithObjects:@802, @229, @522, @712, @628, @84, @412, @726, @284, @699, @1765, @1754, @1528, @2230, @2005, @1494, @1348, @2132, @2040, @2183, nil];
NSLog(@"%@", _theQuestionsSet);

Why is the output not in the same order as inserted?

2013-03-28 16:41:50.178 xxxxxxxx[4011:c07] {(
412,
1754,
628,
726,
1528,
284,
1348,
84,
2005,
699,
522,
712,
1494,
2132,
2230,
1765,
2040,
802,
2183,
229
)}

回答1:


Because an NSMutableSet has no order. An array is ordered; a set is not. (An ordered set sort of bridges the gap, but that's not what you're using.)

Read the fine documentation:

https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSSet_Class/Reference/Reference.html

What's the first sentence?

The NSSet, NSMutableSet, and NSCountedSet classes declare the programmatic interface to an unordered collection of objects.

Unordered. End of story.

See also my book:

http://www.apeth.com/iOSBook/ch10.html#_nsset_and_friends

You can walk through (enumerate) a set with the for...in construct, though the order is of course undefined.

The order is undefined.

(It sounds from your original question as if what you really want is an NSMutableArray that you then shuffle. I have code for that! But that would be a different question.)




回答2:


Because it's not ordered. Use NSMutableOrderedSet if you need that.




回答3:


NSMutableSet order is not maintained. Use NSMutableOrderedSet or NSMutableArray to maintain order



来源:https://stackoverflow.com/questions/15686243/nsmutableset-intput-is-not-in-the-same-order-as-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!