Sort NSArray by NSDictionary value

I am trying to sort an array that will look something like this: (please ignore the fact that these people have gone past life! I just need 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 sorting the output will 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 sorting:

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 sorts it, but from my understanding it is sorting by line. I tried, but after several days of failure trying to write a method that would sort this out for me, I'm still at a loss. What would be the best approach and doing this so that it sorts by a numerical value?

+5
source share
2 answers

, :

[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];
}];
+10

- , .

0

All Articles