Question

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
)}
Was it helpful?

Solution 2

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.)

OTHER TIPS

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top