objective-ccontainersnsmutableorderedset

NSMutableOrderedSet addObject not ordered


I have an NSMutableOrderedSet which contains NSDate objects. Initially, here are the values:

2014-10-08 12:46:48 +0000
2014-10-08 12:46:42 +0000

After calling addObject with 2014-10-08 12:45:40 +0000, I get the following output:

2014-10-08 12:46:42 +0000
2014-10-08 12:46:48 +0000
2014-10-08 12:45:40 +0000

Why aren't they ordered?


Solution

  • an NSMutablOrderedSet is not like a Java TreeSet which is kept sorted. Look at addObject: documentation:

    Appends a given object to the end of the mutable ordered set, if it is not already a member.

    You should manually call

    - (void)sortUsingDescriptors:(NSArray *)sortDescriptors
    

    or

    - (void)sortUsingComparator:(NSComparator)cmptr