【问题标题】:Sort Dictionary of Array Using Predicate使用谓词对数组字典进行排序
【发布时间】:2017-09-15 07:39:09
【问题描述】:

我有一个 json 字典

[
  {
    "allquestions": [
      {
        "question": "First question in 0th index"
      },
      {
        "question": "Second  question in 0th index"
      }
    ]
  },
  {
    "allquestions": [
      {
        "question": "First  question in 1st index"
      }
    ]
  }
]

我需要使用谓词在单个数组中获取键 allquestions 的所有值。

到目前为止我尝试过的是

NSPredicate *combinePagePredicate = [NSPredicate predicateWithFormat:@"allquestions == %@",@"someValue"];

someValue 对解决我的问题有何价值?

【问题讨论】:

  • 你有一个字典数组字典数组。不知何故,我认为有更好的方法来构建您的数据。
  • @mag_zbc 它来自 api 服务。我没有办法改变这个结构。
  • 我不认为谓词会达到您想要的效果,但可能还有其他方法 - 您能否准确说明您希望单个数组包含的内容?
  • @pbasdf allquestions = @[@"第 0 个索引中的第一个问题",@"第 0 个索引中的第二个问题",第 1 个索引中的第一个问题];
  • NSPredicate 不会做任何事情。您必须自己枚举,或者使用valueForKeyPath:,但我不确定它是否真的更快更简单。 NSArray *questions = [array valueForKeyPath:@"allquestions.question"]; NSMutableArray *flattenQuestions = [[NSMutableArray alloc] init]; [questions enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {[flattenQuestions addObjectsFromArray:obj];}]; 所以我的建议:枚举值。它更简单,更容易调试,如果你需要在 3 个月内进行更改,更容易理解你做了什么。

标签: ios objective-c nsarray nspredicate


【解决方案1】:

不完全确定您要达到的目标。如果您想要该字典中所有问题的列表,则分别遍历每个字典,然后对问题进行相同的迭代。将问题添加到数组中,然后过滤该数组。没有尝试过这段代码,但这是一个开始。

NSMutableArray *questions = [[NSMutableArray alloc] init]; 
for (id i in dictionaryArray)
{
    NSArray *arr = i[@"allquestions"];
    for (id x in arr) 
    {
       NSString *currentQuestion = [x objectForKey:@"question"];
       [questions addObject:currentQuestion]; 
    }
}

【讨论】:

  • 我试图使用 NSPredicate 来实现。不是这样。
猜你喜欢
  • 2018-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-30
  • 1970-01-01
  • 1970-01-01
  • 2019-12-07
相关资源
最近更新 更多