Sorting an NSArray by an NSDictionary value

梦想的初衷 提交于 2019-12-04 09:39:46

问题


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;
}

)

and after the sort:

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?


回答1:


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];
}];

Or, using Objective-C's more recent subscripting features:

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



回答2:


Easiest would be storing the age as a number instead of a string.



来源:https://stackoverflow.com/questions/3302222/sorting-an-nsarray-by-an-nsdictionary-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!