0

我有一个 NSArray,里面有 3 个对象。每个对象由 5 个值组成。如何在对象中按日期排序?

result: (
    gg,
    "2012-10-28 01:34:00 +0000",
    "Church Bells",
    "pin_red",
    1
)(
    iu,
    "2008-09-22 17:32:00 +0000",
    "Birthday Song",
    "pin_red",
    1
)(
    "my birthday woo hoo",
    "2012-09-04 19:27:00 +0000",
    "Birthday Song",
    "pin_blue",
    1
)

我正在寻找的结果 - 排序数组应该是这样的。

(
    iu,
    "2008-09-22 17:32:00 +0000",
    "Birthday Song",
    "pin_red",
    1
)
(
    "my birthday woo hoo",
    "2012-09-04 19:27:00 +0000",
    "Birthday Song",
    "pin_blue",
    1
)
(
    gg,
    "2012-10-28 01:34:00 +0000",
    "Church Bells",
    "pin_red",
    1
)

我从我的 nsdictionary 对象中获取这个数组。

dictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:stringsPlistPath];
stringsMutableArray = [[NSMutableArray alloc] initWithObjects:nil];

        for (id key in dictionary) 
        {
            [stringsMutableArray addObject:[dictionary objectForKey:key]];
        }
4

2 回答 2

2

试试这个:

NSArray *sortedArray = [result sortedArrayUsingComparator: ^(id obj1, id obj2) {
    NSArray *arr1 = (NSArray *)obj1;
    NSArray *arr2 = (NSArray *)obj2;
    NSDate *date1 = arr1[1];
    NSDate *date2 = arr2[1];

    return [date1 compare:date2];
}];

此代码假定您实际上有一个数组数组,并且日期是 NSDate 对象,始终位于内部数组的索引 1 处。如果按您想要的相反顺序排序,请交换两个日期以进行日期比较。

于 2012-10-28T04:56:26.813 回答
0

这是解决您的问题的类似问题:Sort NSArray of date strings or objects

我将从下面的上述链接中粘贴答案:

将日期作为 NSDate 对象存储在 NS(Mutable)Array 中,然后使用 [ -[NSArray sortedArrayUsingSelector:][1] 或 [ ][1] 并作为参数-[NSMutableArray sortUsingSelector:]传递。@selector(compare:)[ -[NSDate compare:]][2] 方法将为您按升序排列日期。这比创建 NSSortDescriptor 简单,也比编写自己的比较函数简单得多。(NSDate 对象知道如何相互比较,至少与我们希望使用自定义代码完成的效率一样高。)

[1]: http: //developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html#//apple_ref/occ/instm/NSMutableArray/sortUsingSelector:[2]: http: //developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html#//apple_ref/occ/instm/NSDate/compare

于 2012-10-28T04:34:18.563 回答