【问题标题】:Sorting array of multiple dictionaries对多个字典的数组进行排序
【发布时间】:2013-01-07 09:26:52
【问题描述】:

我的数组包含每个数组对象的三个字典。

{
    avg = {
        avg1 = 50;
        avg2 = 60;
    };

    posts =         {
        alcoholContent = 450;
        name = "BBB";
        origin = United States;

    };

    reviews =  {

        rev1 = "Test review 1";
        rev2 = "Test review 2";
    };
}

{
    avg = {
        avg1 = 30;
        avg2 = 20;
    };

    posts =         {
        alcoholContent = 550;
        name = "AAA";
        origin = United States;

    };

    reviews =  {

        rev1 = "Test review 1";
        rev2 = "Test review 2";
    };
}

我想通过键 "name" (后字典)对数组进行排序。 我该怎么做?

我尝试了使用排序描述符的普通排序方法,但没有奏效

【问题讨论】:

  • 排序描述符应该可以工作。你能发布一个你做了什么的例子吗?
  • 感谢您的回答。这就是我所做的 NSSortDescriptor *sortDescriptor; sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" 升序:YES]; NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor]; NSArray *sortedArray; sortedArray = [arrItems sortedArrayUsingDescriptors:sortDescriptors];

标签: iphone objective-c ios ios4


【解决方案1】:

尝试 sortUsingComparator:

[array sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    NSDictionary *dict1 = obj1;
    NSDictionary *dict2 = obj2;

    NSString *string1 = [[dict1 objectForKey:@"posts"] objectForKey:@"name"];
    NSString *string2 = [[dict2 objectForKey:@"posts"] objectForKey:@"name"];

    return [string1 compare:string2];
}];

【讨论】:

  • 没问题。如果您认为这是一个很好的答案,请点赞;)
猜你喜欢
  • 2020-05-30
  • 1970-01-01
  • 1970-01-01
  • 2018-04-09
  • 2016-03-14
  • 1970-01-01
  • 2011-11-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多