Sort NSArray of date strings or objects Sort NSArray of date strings or objects objective-c objective-c

Sort NSArray of date strings or objects


If I have an NSMutableArray of objects with a field "beginDate" of type NSDate I am using an NSSortDescriptor as below:

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"beginDate" ascending:TRUE];[myMutableArray sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];[sortDescriptor release];


Store the dates as NSDate objects in an NS(Mutable)Array, then use -[NSArray sortedArrayUsingSelector: or -[NSMutableArray sortUsingSelector:] and pass @selector(compare:) as the parameter. The -[NSDate compare:] method will order dates in ascending order for you. This is simpler than creating an NSSortDescriptor, and much simpler than writing your own comparison function. (NSDate objects know how to compare themselves to each other at least as efficiently as we could hope to accomplish with custom code.)


You may also use something like the following:

//Sort the array of items by  date    [self.items sortUsingComparator:^NSComparisonResult(id obj1, id obj2){        return [obj2.date compare:obj1.date];    }];

But this does assume that the date is stored as a NSDate rather a NString, which should be no problem to make/do. Preferably, I recommend also storing the data in it's raw format. Makes it easier to manipulate in situations like this.