0

I am having the array of Dictionary and it's in the formats of,

 resultsArray = { 

id = 1;
name = test;
distance = 11.5;

id = 2;
name = test1;
distance = 0.5;

id = 3;
name = test2;
distance = 2.5;

id = 4;
name = test4;
distance = 1.5;

}

I want to sort the array using the distance key and my distance in the float type. So how can i sort the array using distance is in the ascending order?.

So i am expecting the results like this,

resultsArray = { 

id = 2;
name = test1;
distance = 0.5;

id = 4;
name = test4;
distance = 1.5;

id = 3;
name = test2;
distance = 2.5;

id = 1;
name = test;
distance = 11.5;

}

Please help me out.

Thanks!

4

3 回答 3

1
NSArray *sortedArray = [resultsArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"distance" ascending:YES]]];
于 2012-06-29T21:49:20.673 回答
0
[resultArray sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    return [[obj1 objectForKey:@"distance"] compare:[obj2 objectForKey:@"distance"]];
}];
于 2012-06-29T21:47:13.020 回答
0

还有一种解决方案:

@interface NSDictionary(sortingByDistance)
-(NSComparisonResult) compareByDistance:(NSDictionary*)dict;
@end
@implementation NSDictionary(sortingByDistance)
-(NSComparisonResult) compareByDistance:(NSDictionary*)dict {
    return [[self objectForKey:@"distance"] compare:[dict objectForKey:@"distance"]];
}
@end

现在对数组进行排序,您可以使用sortUsingSelector方法:

[resultArray sortUsingSelector:@selector(compareByDistance:)];
于 2012-06-29T22:11:30.217 回答