orthehelper
orthehelper

Reputation: 4079

NSMutableArray Sort Task

i have NSMutableArray contains NSArray Objects, it looks like this

(
    "2012-10-10 13:13:29 +0000",
    cc5772389efc1f93bedaab872bad542a1c8432af,
    "{\n    size             = {360, 480}\n    CGImage.size     = {480, 360}\n    imageOrientation = UIImageOrientationRight\n}"
),
    (
    "2012-10-10 13:13:37 +0000",
    6c09d99f940af8e7d1d1392d28abee2133b7ac75,
    "{\n    size             = {360, 480}\n    CGImage.size     = {480, 360}\n    imageOrientation = UIImageOrientationRight\n}"
),
    (
    "2012-10-10 13:13:19 +0000",
    0165776bd9e96e640c905471ddb8630c22a8911c,
    "{\n    size             = {360, 480}\n    CGImage.size     = {480, 360}\n    imageOrientation = UIImageOrientationRight\n}"
)

each NSArray object contains NSDate object at the first index, i want to sort thisNSMutableArray from the older to the newest.

any idea?

Upvotes: 0

Views: 155

Answers (2)

vikingosegundo
vikingosegundo

Reputation: 52227

You can use NSMutableArray's -sortUsingComparator:.

sortUsingComparator:
Sorts the array using the comparison method specified by a given NSComparator Block.

- (void)sortUsingComparator:(NSComparator)cmptr
Parameters cmptr A comparator block.

[array sortUsingComparator: ^(NSArray *array1, NSArray *array2) {
    NSDate *date1 = [array1 objectAtIndex:0];
    NSDate *date2 = [array2 objectAtIndex:0];
    return [date1 compare:date2];
}];

to reverse the order, you can simply return [date2 compare:date1]

Upvotes: 4

Parag Bafna
Parag Bafna

Reputation: 22930

use -sortedArrayUsingFunction:context:

NSInteger dateSort(id obj1, id obj2, void *context)
{
    NSData *date1 = [obj1 objectAtIndex:0] ;
    NSData *date2 = [obj2 objectAtIndex:0] ;
    return [date1 compare:date2];
}
NSArray *sortedArray = [array sortedArrayUsingFunction:dateSort context:NULL];

Upvotes: 0

Related Questions