开发者

Sort Dictionaries in Array?

I need to sort an nsmutablearray of nsdictionaries, using a keyed object from the dictionary. The object is an开发者_开发知识库 NSNumber. How would I sort the dictionaries in the nsmutablearray with the first object being the highest nsnumber?

Thanks!


With a custom comparator defined with a block (you can go other ways but this is quite compact):

NSComparator mysort = ^(id dict1, id dict2) {
    NSNumber n1 = [dict1 objectForKey:@"key"];
    NSNumber n2 = [dict2 objectForKey:@"key"];
    return (NSComparisonResult)[n1 compare:n2];
};

[yourArray sortUsingComparator:mysort];


That code seems a bit off. Here is one that works.

[theMutableArrayThatWillBeSorted sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    NSNumber* n1 = [obj1 objectForKey:@"key"];
    NSNumber* n2 = [obj2 objectForKey:@"key"];

    return [n1 compare:n2];     
}];
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜