0

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?

Lord Zsolt
  • 6,492
  • 9
  • 46
  • 76

3 Answers3

2

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
Jack
  • 131,802
  • 30
  • 241
  • 343
  • So basically it's an `NSMutableArray` which doesn't let me insert the same element twice? – Lord Zsolt Oct 08 '14 at 13:29
  • It has all the common set operations: union, intersection, difference. They should be rather more efficient when working with other sorted sets (or sets in general) – Jack Oct 08 '14 at 13:31
  • Exactly. What order did you expect it to automatically assume? Ordered means that it will keep track of the position of items. If you change that position out will remember them. It doesn't mean "sorted" which is what I think you thought. – Fogmeister Oct 08 '14 at 13:32
  • Yeah, I thought it was sorted set, just like Java/C++ has. – Lord Zsolt Oct 08 '14 at 13:46
1

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;
}];
Chris
  • 7,270
  • 19
  • 66
  • 110
  • Yeah, I just did that. I have been trying to wrap my head around `NSOrderedSet`in Objective-C, but I can't seem to get it. In Java or C++, when inserting something, it got sorted automatically. – Lord Zsolt Oct 08 '14 at 13:27
0

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.

uchuugaka
  • 12,679
  • 6
  • 37
  • 55