问题描述
我有一个字典数组。
我想根据键过滤数组。
我试过这个:
NSPredicate * predicate = [NSPredicate predicateWithFormat:@(SPORT ==%@)足球];
NSArray * filteredArray = [data filteredArrayUsingPredicate:predicate];
这不工作,我没有结果。我想我做错了。我知道这是如果SPORT是一个ivar的方法。我认为这可能是不同的,如果它是一个键。
我找不到一个例子。
感谢
更新 b
我在搜索的字符串周围添加了引号。
NSPredicate * predicate = [NSPredicate predicateWithFormat:@ SPORT =='%@'),@Football];
它仍然无法工作。
更新2
解决了问题。我实际上不得不删除单引号,这似乎违反了指南说。
我真正的问题是,我有一个嵌套数组,我没有实际评估词典。骨头移动。
它应该工作 - 只要数据变量实际上是一个数组,
NSArray * data = [NSArray arrayWithObject:[NSMutableDictionary dictionaryWithObject:@fooforKey:@BAR]];
NSArray * filtered = [data filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@(BAR ==%@),@foo]];
在此情况下筛选包含字典。
(不需要引用%@,这是在NSPredicate创建对象时完成的。)
I have an array of dictionaries.
I want to filter the array based on a key.
I tried this:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(SPORT == %@)", @"Football"];
NSArray *filteredArray = [data filteredArrayUsingPredicate:predicate];
This doesn't work, I get no results. I think I'm doing something wrong. I know this is the method if "SPORT" was an ivar. I think it is probably different if it is a key.
I haven't been able to find an example however.
Thanks
Update
I added quotes around the string I am searching for.
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(SPORT == '%@')", @"Football"];
It still does not work.
Update 2
Solved it. I actually had to remove the single quotes, which seems to go against what the guide says.
My real problem is I had a nested array and I wasn't actually evaluating the dictionaries. Bone head move.
It should work - as long as the data variable is actually an array containing a dictionary with the key SPORT
NSArray *data = [NSArray arrayWithObject:[NSMutableDictionary dictionaryWithObject:@"foo" forKey:@"BAR"]];
NSArray *filtered = [data filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(BAR == %@)", @"foo"]];
Filtered in this case contains the dictionary.
(the %@ does not have to be quoted, this is done when NSPredicate creates the object.)
这篇关于使用NSPredicate基于NSDictionary键过滤NSArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!