Using NSPredicate get only values of a particular key from an array of dictionaries

大兔子大兔子 提交于 2019-12-12 02:23:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!