开发者

how to sort an Array of Dictionaries

开发者 https://www.devze.com 2023-02-25 18:05 出处:网络
I need to sort an array of dictionaries, using a keyed object from the dictionary. The object is an NSString that contains a float. I used an NSSortDescriptor but it sorts alphabetica开发者_运维百科ll

I need to sort an array of dictionaries, using a keyed object from the dictionary. The object is an NSString that contains a float. I used an NSSortDescriptor but it sorts alphabetica开发者_运维百科lly. How would I make a custom selector or comparator to do it numerically?


This should give you an idea of how this can be done using NSComparator blocks:

[array sortUsingComparator:(NSComparator)^(id obj1, id obj2){
    double firstValue = [[obj1 objectForKey:@"someKey"] doubleValue];
    double secondValue = [[obj2 objectForKey:@"someKey"] doubleValue];
    double valueDiff = firstValue - secondValue;
    return (valueDiff == 0) ? NSOrderedSame : (valueDiff < 0) ? NSOrderedAscending : NSOrderedDescending;
}];

obj1 and obj2 are id pointers to a pair of dictionary objects in your array. Whatever you do within the NSComparator block is up to you. As long as you return either NSOrderedSame, NSOrderedAscending or NSOrderedDescending.

In general you might be better advised using a real numeric data type (à la [NSNumber numberWith...:x]) to hold such floating point values, than a string.

0

精彩评论

暂无评论...
验证码 换一张
取 消