NSMutableArray排序任务

时间:2012-10-10 13:20:57

标签: objective-c ios cocoa-touch nsmutablearray nsarray

NSMutableArray包含NSArray个对象,它看起来像这样

(
    "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}"
)

每个NSArray对象在第一个索引处包含NSDate个对象,我想从旧版本到最新版本对此NSMutableArray进行排序。

任何想法?

2 个答案:

答案 0 :(得分:4)

您可以使用NSMutableArray的-sortUsingComparator:

  

sortUsingComparator:
  使用给定NSComparator块指定的比较方法对数组进行排序。

     

- (void)sortUsingComparator:(NSComparator)cmptr
  参数 cmptr comparator阻止。

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

要撤消订单,您只需返回[date2 compare:date1]

即可

答案 1 :(得分:0)

使用-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];