1

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
)}
PeterK
  • 4,243
  • 4
  • 44
  • 74

3 Answers3

4

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

Desdenova
  • 5,326
  • 8
  • 37
  • 45
  • He's not saying he wants it ordered, he's saying that the order that it was inserted is not the order it is held. – Nathan White Mar 28 '13 at 15:49
  • 3
    The notion of ordering in a set is meaningless. – matt Mar 28 '13 at 15:49
  • Just so i understand if i insert objects in a specific order it will never come out sorted unless i am not using NSMutableOrderedSet? ...meaning i do not need to shuffle the objects? – PeterK Mar 28 '13 at 15:51
  • 1
    @peterk Unordered is not shuffled; if you need the objects shuffled, you will need an ordered collection AND you will need to shuffle them yourself. – bbum Mar 28 '13 at 18:15
  • @bbum I realized it when i tested, thanks :-) – PeterK Mar 29 '13 at 09:20
3

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

matt
  • 515,959
  • 87
  • 875
  • 1,141
1

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

RyanCodes
  • 175
  • 1
  • 5