简体   繁体   English

订购NSArray字典-目标c

[英]Order NSArray of Dictionaries - Objective c

I have an array of dictionaries that looks something like this 我有一系列看起来像这样的字典

({order:1; name:foo},{order:0; name:bar}...)

And I want to order this NSArray of dictionaries by the key "order". 我想通过键“ order”对这个NSArray字典进行排序。

I know I am going to have to loop though it and then add it to a new array but Im not quite sure how to set it up? 我知道我将不得不循环它,然后将其添加到一个新的数组中,但是我不太确定如何设置它?

Thanks for the help 谢谢您的帮助

There are several possible ways to do this. 有几种方法可以做到这一点。

Here's one: 这是一个:

NSArray *unsortedArray = ... // your unsorted array of dictionaries
NSSortDescriptor *sortBy = [NSSortDescriptor sortDescriptorWithKey:@"order" ascending:YES];
NSArray *sorted = [unsortedArray sortedArrayUsingDescriptors:@[ sortBy ]];

Here's another: 这是另一个:

NSArray *unsortedArray = ... // your unsorted array of dictionaries
NSArray *sorted = [unsortedArray sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *dic1, NSDictionary *dic2) {
    NSNumber *order1 = dic1[@"order"];
    NSNumber *order2 = dic2[@"order"];

    return [order1 compare:order2];
}];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM