【问题标题】:Check if value exists for a particular key in an array of dictionaries in ios检查ios中字典数组中特定键的值是否存在
【发布时间】:2015-12-27 00:55:38
【问题描述】:

我有一个名为sourceDataNSMutableArray,其中包含许多具有相同键的字典对象:ID、NAME、CONTENT。

 [ //sourceData
   {ID:1, NAME:@"Bob", CONTENT:@"words"},
   {ID:2, NAME:@"Bob", CONTENT:@"words"},
   {ID:3, NAME:@"Bob", CONTENT:@"words")
 ];

我有另一个相同的数组,称为dataToAdd。我想做的是遍历数组dataToAdd,如果对象没有相同的ID值,则仅将对象添加到sourceData中。

换句话说,如果数组sourceData 包含一个ID 为X 的字典对象,我该如何检查它。

【问题讨论】:

    标签: ios objective-c arrays dictionary


    【解决方案1】:

    您应该使用谓词来过滤数组。

    NSArray *filtered = [sourceData filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(ID == %@)", @(ID_YOU_WANT_TO SEARCH)]];
    

    这将返回包含请求 ID 的所有字典的数组。

    【讨论】:

      【解决方案2】:

      在您的sourceData for 字典上运行 for-in 循环,并获取键的值,在本例中为 ID。

      它应该看起来像这样

      for (NSDictionary *aDict in sourceData) {
         if ([[aDict objectForKey:@"ID"] intValue] == 1) {
             // id was indeed 1, replace '1', with the id that you're looking for
         }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-25
        • 2011-05-29
        • 2022-06-14
        • 1970-01-01
        • 1970-01-01
        • 2015-11-26
        • 2012-11-16
        • 1970-01-01
        相关资源
        最近更新 更多