按NSDictionary值对NSArray进行排序

时间:2010-07-21 17:50:12

标签: objective-c sorting nsarray nsdictionary

我正在尝试排序一个看起来像这样的数组: (请忽略这些人已经过了任何生活年龄的事实!我只需要大量的数字)

NSDictionary *person1 = [NSDictionary dictionaryWithObjectsAndKeys:@"sam",@"name",@"28.00",@"age",nil];
NSDictionary *person2 = [NSDictionary dictionaryWithObjectsAndKeys:@"cody",@"name",@"100.00",@"age",nil];
NSDictionary *person3 = [NSDictionary dictionaryWithObjectsAndKeys:@"marvin",@"name",@"299.00",@"age",nil];
NSDictionary *person4 = [NSDictionary dictionaryWithObjectsAndKeys:@"billy",@"name",@"0.0",@"age",nil];
NSDictionary *person5 = [NSDictionary dictionaryWithObjectsAndKeys:@"tammy",@"name",@"54.00",@"age",nil];

NSMutableArray *arr = [[NSMutableArray alloc] initWithObjects:person1,person2,person3,person4,person5,nil];

// before sort
NSLog(@"%@",arr);

NSSortDescriptor *ageSorter = [[NSSortDescriptor alloc] initWithKey:@"age" ascending:YES];
[arr sortUsingDescriptors:[NSArray arrayWithObject:ageSorter]];

// after sort
NSLog(@"%@",arr);

现在在排序之前,输出将是:

2010-07-21 10:46:31.898 Sorting[70673:207] (
    {
    age = "28.00";
    name = sam;
},
    {
    age = "100.00";
    name = cody;
},
    {
    age = "299.00";
    name = marvin;
},
    {
    age = "0.0";
    name = billy;
},
    {
    age = "54.00";
    name = tammy;
}

并在排序后:

2010-07-21 10:46:31.900 Sorting[70673:207] (
    {
    age = "0.0";
    name = billy;
},
    {
    age = "100.00";
    name = cody;
},
    {
    age = "28.00";
    name = sam;
},
    {
    age = "299.00";
    name = marvin;
},
    {
    age = "54.00";
    name = tammy;
}

正如你所看到它对它进行排序,但从我的理解它是按字符串排序。我已经尝试了但是在尝试编写一种方法失败了几天之后,我仍然不知所措。什么是最好的方法并完成这个,所以它按数值排序?

2 个答案:

答案 0 :(得分:10)

虽然我在这里质疑字符串的使用,但使用该数据的最简单方法是:

[array sortedArrayUsingComparator:^(NSDictionary *item1, NSDictionary *item2) {
    NSString *age1 = [item1 objectForKey:@"age"];
    NSString *age2 = [item2 objectForKey:@"age"];
    return [age1 compare:age2 options:NSNumericSearch];
}];

或者,使用Objective-C的最新下标功能:

[array sortedArrayUsingComparator:^(NSDictionary *item1, NSDictionary *item2) {
    return [item1[@"age"] compare:item2[@"age"] options:NSNumericSearch];
}];

答案 1 :(得分:0)

最简单的方法是将年龄存储为数字而不是字符串。