使用 NSPredicate 根据 NSDictionary 键过滤 NSArray [英] Using NSPredicate to filter an NSArray based on NSDictionary keys

查看:33
本文介绍了使用 NSPredicate 根据 NSDictionary 键过滤 NSArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字典数组.

我想根据键过滤数组.

我试过了:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(SPORT ==  %@)", @"Football"];

NSArray *filteredArray = [data filteredArrayUsingPredicate:predicate];

这不起作用,我没有得到任何结果.我想我做错了什么.如果SPORT"是 ivar,我知道这就是方法.我想如果是钥匙的话可能就不一样了.

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.

谢谢

更新

我在要搜索的字符串周围添加了引号.

I added quotes around the string I am searching for.

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(SPORT ==  '%@')", @"Football"];

还是不行.

更新 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.

推荐答案

它应该可以工作——只要数据变量实际上是一个包含带有键 SPORT 的字典的数组

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.

(%@ 不必被引用,这是在 NSPredicate 创建对象时完成的.)

(the %@ does not have to be quoted, this is done when NSPredicate creates the object.)

这篇关于使用 NSPredicate 根据 NSDictionary 键过滤 NSArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆