Search code examples
iosobjective-cnsarraynsdictionary

Find NSDictionary containing specific value in NSArray (iOS)


I have a NSArray("address_components") of multiple NSDictionary. Each NSDictionary contains one NSArray("types") of NSString values. Like this..

"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"
    );
}
);

How can I get the dictionary that contains the array with string "locality". In this example I want to get the dictionary..

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

Thank you :)


Solution

  • You need to predicate your address array like this

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY types CONTAINS[c] %@", @"locality"];
    NSArray *arr = [yourArray filteredArrayUsingPredicate:predicate];