NSMutableOrderedSet addObject not ordered

653 Views Asked by At

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?

3

There are 3 best solutions below

4
On BEST ANSWER

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
1
On

I don't have an answer to why they're not ordered, but you can sort them by date by doing that following:

NSArray *mySortedArray =[myArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {

    NSComparisonResult result;

    NSDate *dateA = (NSDate*)obj1;
    NSDate *dateB = (NSDate*)obj2;

    result = [dateA compare:dateB];

    return result;
}];
0
On

It's basically like NSMutable array but with no duplicate objects. The docs say addObjec: adds it to the end. You need to apply sorting using one of the following methods

– sortUsingDescriptors:

– sortUsingComparator:

– sortWithOptions:usingComparator:

– sortRange:options:usingComparator:

Think of it semantically the same as taking an NSMutableSet which has no order, creating an NSMutableArray from that and then not liking the order of the array. You need to tell it how to sort. The NSMutableOrderedSet doesnt have a DWIM (do what I mean) algorithm baked in, you tell it how.