问题描述
我正在尝试对看起来像这样的数组进行排序:(请忽略这些人已经过了任何生活年龄的事实!我只需要大量的人)
I'm trying to sort an array that would look something like this:(please ignore the fact these people are well past any living age! I just needed large numbers)
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);
现在排序之前的输出将是:
Now before sort the output would be:
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;
}
)
您可以看到它确实对它进行了排序,但是据我了解,它是按字符串排序的.我已经尝试过了,但是在尝试编写将对我进行排序的方法失败几天后,我仍然感到茫然.最好的方法是什么,完成它,以便按数值排序?
As you can see it does sort it, but from my understanding it's sorting by string. I've tried but after a few days of failure of trying to write a method that would sort this for me im still at a loss. What would be the best approach and accomplishing this so it sorts by a numeric value?
推荐答案
尽管我在这里质疑字符串的使用,但是使用该数据的最简单方法是:
Although I question the use of strings here, the simplest way to work with that data with be:
[array sortedArrayUsingComparator:^(NSDictionary *item1, NSDictionary *item2) {
NSString *age1 = [item1 objectForKey:@"age"];
NSString *age2 = [item2 objectForKey:@"age"];
return [age1 compare:age2 options:NSNumericSearch];
}];
或者,使用Objective-C的最新下标功能:
Or, using Objective-C's more recent subscripting features:
[array sortedArrayUsingComparator:^(NSDictionary *item1, NSDictionary *item2) {
return [item1[@"age"] compare:item2[@"age"] options:NSNumericSearch];
}];
这篇关于按NSDictionary值对NSArray进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!