对包含日期的NSStrings进行排序

时间:2015-08-09 12:18:31

标签: objective-c sorting

我有一系列词典。每个字典都有一个字符串对象,用于键@" date"。我需要按此日期对数组进行排序,降序。我怎么能以最好的方式做到这一点?

3 个答案:

答案 0 :(得分:2)

您可以创建NSSortDescriptor,例如:

NSSortDescriptor *sorter = [NSSortDescriptor sortDescriptorWithKey:@"date" ascending:YES];
[array sortUsingDescriptors:@[sorter]];

这将使用字符串比较来比较您的日期字符串。如果正确且一致地格式化日期字符串,它应该有效。

答案 1 :(得分:1)

如果我理解了这个阵列的结构,我希望这个答案有所帮助! :)

我使用这种方法对一个数组进行排序,该数组包含一个数组,该数组包含最终保存了一个我希望按顶部数组排序的字符串。显然,简单的事情并不起作用。但我碰到了这个:

- (void)sortUsingComparator:(NSComparator)cmptr;

在您的情况下,我希望,这是您使用的:

NSMutableArray *arrayItems = [NSMutableArray arrayWithObjects:
                              @{@"date":[NSDate date]},
                              @{@"date":[NSDate dateWithTimeIntervalSinceNow: 60*60*45]},
                              @{@"date":[NSDate dateWithTimeIntervalSinceNow: 60*60*25]},
                              @{@"date":[NSDate date]},
                              @{@"date":[NSDate dateWithTimeIntervalSinceNow: 60*60*5]},
                              @{@"date":[NSDate dateWithTimeIntervalSinceNow: 60*60*32]},
                              @{@"date":[NSDate date]},
                              @{@"date":[NSDate dateWithTimeIntervalSinceNow: 60*60]},
                              nil];
[arrayItems sortUsingComparator:^NSComparisonResult(id obj1, id obj2) { //obj1 and obj2 are objects in the list of the array. so in your case a list of dictionaries, so obj1 and obj2 are dictionaries, mutable
    //And now, which is why you would use this block to sort your objects, there you'll access each date, or object, you want to have the 'power' to sort the objects inside the caller, in this case arrayItems
    NSDate *date1 = [obj1 objectForKey: @"date"];
    NSDate *date2 = [obj2 objectForKey: @"date"];

    //And now you compare the two of whom is larger
    return [date1 compare: date2];

}];
NSLog( @"%@", arrayItems);

我希望这有帮助,或者暗示你回答:)

答案 2 :(得分:0)

最好的方法是将这些字符串格式化为NSDate个对象并使用compare:方法。