对包含NSMutableDictionaries

时间:2015-06-05 20:31:24

标签: ios objective-c sorting nsmutablearray

我试图找出对包含n个字典的数组进行排序的最佳/最有效方法。每个字典中的一个键/值对是日期字段。将所有字典添加到数组后,我想按降序排列数组。

例如,我有这样的代码:

NSMutableArray *myArray = [[NSMutableArray alloc] init];

NSMutableDictionary *dictionary1 = [[NSMutableDictionary alloc] init];
    NSDate *today = [NSDate date];
    [dictionary1 setObject:today forKey:@"date"];
    [dictionary1 setObject:@"Another value" forKey:@"anotherKey"];

[myArray addObject:dictionary1];

NSMutableDictionary *dictionary2 = [[NSMutableDictionary alloc] init];
    NSDate *tomorrow = [[NSDate date] dateByAddingTimeInterval:60*60*24];
    [dictionary2 setObject:tomorrow forKey:@"date"];
    [dictionary2 setObject:@"Yet another value" forKey:@"anotherKey"];

[myArray addObject:dictionary2];

现在我需要按降序日期对myArray进行排序。 (数组索引0应该是最新日期)

注意:在我的实际项目中,我没有以这种方式创建和添加词典。但是,例如,为了查看日期如何存储在字典中,我们假设我已将这两个放入数组中。

2 个答案:

答案 0 :(得分:3)

您可以在此处使用NSSortDescriptors:

NSMutableArray *myArray = [[NSMutableArray alloc] init];

NSMutableDictionary *dictionary1 = [[NSMutableDictionary alloc] init];
NSDate *today = [NSDate date];
[dictionary1 setObject:today forKey:@"date"];
[dictionary1 setObject:@"Another value" forKey:@"anotherKey"];

[myArray addObject:dictionary1];

NSMutableDictionary *dictionary2 = [[NSMutableDictionary alloc] init];
NSDate *tomorrow = [[NSDate date] dateByAddingTimeInterval:60*60*24];
[dictionary2 setObject:tomorrow forKey:@"date"];
[dictionary2 setObject:@"Yet another value" forKey:@"anotherKey"];

[myArray addObject:dictionary2];

NSSortDescriptor *sortDesciptor = [NSSortDescriptor sortDescriptorWithKey:@"date" ascending:NO];

//Create new sorted array
NSArray *sortedArray = [myArray sortedArrayUsingDescriptors:@[sortDesciptor]];

//Or sort your mutable one
[myArray sortUsingDescriptors:@[sortDesciptor]];

答案 1 :(得分:1)

有很多方法可以做到这一点。您可以使用NSSortDescriptor,如Krivoblotsky所说。

您还可以使用#!/usr/bin/env ruby h, m, s = 12, 07, 13 $_.gsub!(/(\d\d):(\d\d):(\d\d)/) do hour, min, sec = [ $1.to_i + h, $2.to_i + m, $3.to_i + s ] if sec >= 60 then min += 1; sec -=60; end #only needed if s > 0 if min >= 60 then hr += 1; min -=60; end #must do before seconds offset '%02d:%02d:%02d' % [hour, min, sec] end NSMutableArray方法。代码看起来像这样:

sortUsingComparator

[myArray sortUsingComparator ^(NSDictionary *obj1, NSDictionary *obj2) { return [obj1["date"] compare: obj2["date"]] } ]; 方法需要sortUsingComparator块。

NSComparator接受两个id类型的对象,并返回NSComparator

NSComparisionResult

由于NSDate支持compare方法,你可以编写1行比较器块来获取每个字典的日期条目,并返回比较它们的结果。