【发布时间】:2010-07-21 17:50:12
【问题描述】:
我正在尝试对一个看起来像这样的数组进行排序: (请忽略这些人已经过了任何年龄的事实!我只需要大量的人)
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;
}
)
如您所见,它确实对其进行了排序,但据我了解,它是按字符串排序的。我已经尝试过,但是在尝试编写一种可以为我排序的方法失败了几天之后,我仍然不知所措。什么是最好的方法并完成此操作,以便按数值排序?
【问题讨论】:
-
为什么不将年龄存储为数字? [NSNumber numberWithFloat:28.0f];
-
因为我正在使用的实际脚本是使用 JSON 提取的,所以它作为字符串对象出现,否则我会:)
标签: objective-c sorting nsarray nsdictionary