问题
I do not know the values. I only know the key.
arrTripCat :
(
{ tripcategory = "general_tourism"; },
{ tripcategory = nightlife; },
{ tripcategory = "art_museums"; },
{ tripcategory = nightlife; },
{ tripcategory = architecture; },
{ tripcategory = nightlife; }
);
The NSPredicate
I tried :
NSArray *arrTripCat = [NSArray arrayWithArray:[self.dictSearchResult objectForKey:@"TripCategories"]];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY SELF.@allKeys contains[cd] %@",@"tripcategory"];
NSMutableArray *filteredArray = [[NSMutableArray alloc] init];
[filteredArray addObjectsFromArray:[arrTripCat filteredArrayUsingPredicate:predicate]];
after this, the filteredArray
still has all of the data in the same format as before.
filteredArray:
(
{ tripcategory = "general_tourism"; },
{ tripcategory = nightlife; },
{ tripcategory = "art_museums"; },
{ tripcategory = nightlife; },
{ tripcategory = architecture; },
{ tripcategory = nightlife; }
);
The end result I'm looking to get is to have all of the values for the tripcategory
key put into an array. i.e.
( general_tourism, nightlife, art_museums, architecture )
回答1:
You don't need a predicate because you aren't actually filtering, all you need is:
NSArray *tripCategories = [arrTripCat valueForKey:@"tripcategory"];
回答2:
You don't want to filter, you want to fold the results, so using a predicate doesn't serve your purpose. In plain Cocoa, you can do:
NSMutableArray *results = @[].mutableCopy;
for (NSDictionary *dict in arrTripCat) {
[results addObject:dict[@"tripcategory"];
}
This will give you ( general_tourism, nightlife, art_museums, architecture ).
来源:https://stackoverflow.com/questions/23009305/using-nspredicate-get-only-values-of-a-particular-key-from-an-array-of-dictionar