在NSArray(iOS)中查找包含特定值的NSDictionary

时间:2016-07-16 10:12:29

标签: ios objective-c nsarray nsdictionary

我有NSArray(“address_components”)多个NSDictionary。每个NSDictionary包含一个NSArray(“类型”)的NSString值。像这样......

"address_components" =         (
{
    "long_name" = "Perumbavoor Puthencruz Road";
    "short_name" = "Perumbavoor Puthencruz Rd";
    types =                 (
        route
    );
},
{
    "long_name" = Vengola;
    "short_name" = Vengola;
    types =                 (
        locality,
        political
    );
},
{
    "long_name" = Ernakulam;
    "short_name" = EKM;
    types =                 (
        "administrative_area_level_2",
        political
    );
},
{
    "long_name" = Kerala;
    "short_name" = KL;
    types =                 (
        "administrative_area_level_1",
        political
    );
},
{
    "long_name" = India;
    "short_name" = IN;
    types =                 (
        country,
        political
    );
},
{
    "long_name" = 683556;
    "short_name" = 683556;
    types =                 (
        "postal_code"
    );
}
);

如何获取包含字符串“locality”的数组的字典。在这个例子中我想得到字典..

{
  "long_name" = Vengola;
  "short_name" = Vengola;
   types =(
      locality,
      political
   );
}

谢谢:)

4 个答案:

答案 0 :(得分:2)

您需要sd.getSomethingClass(); 这样的地址数组

predicate

答案 1 :(得分:2)

使用此代码

NSArray *myArray = [yourAddressDict valueForKey:"address_components"];


 NSMutableArray *NewArray = [NSMutableArray array];

    for (NSDictionary *ob in myArray) {
        NSArray *arraylocality = [ob valueForKey:@"types"];
         BOOL isthere=  [arraylocality containsObject:@"locality"];
        if (isthere) {
            [NewArray addObject:ob];
        }

    }

 NSLog(@"%@",NewArray);

答案 2 :(得分:0)

您可以检查数组是否包含字典或机器人:

for(int i=0; i<[arr count];i++){
if([arr[i] isKindOfClass:[NSDictionary Class]]){
NSDictionary *dic=arr[i];
NSLog("%@",dic);
}
}

答案 3 :(得分:0)

这里你去:

NSArray *list = @[
              @{
                  @"long_name" : @"Perumbavoor Puthencruz Road",
                  @"short_name" : @"Perumbavoor Puthencruz Rd",
                  @"types" : @[@"route"]
                  },
              @{
                    @"long_name" : @"Vengola",
                    @"short_name" : @"Vengola",
                    @"types" : @[@"locality", @"political"]
                    },
              @{
                  @"long_name" : @"Ernakulam",
                  @"short_name" : @"EKM",
                  @"types" :                 @[
                          @"administrative_area_level_2",
                          @"political"]
                  }
              ];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.types CONTAINS 'locality'"];
NSArray *result = [list filteredArrayUsingPredicate:predicate];
NSLog(@"result: %@", result);

结果:

{
        "long_name" = Vengola;
        "short_name" = Vengola;
        types =         (
            locality,
            political
        );
    }