使用NSPredicate过滤NSDray对象的NSArray [英] Filtering NSArray of NSDictionary objects using NSPredicate

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

问题描述

我有一个NSDray的NSDictionary对象。我想使用NSPredicate根据字典的键过滤数组。我一直在做这样的事情:

I have an NSArray of NSDictionary objects. I want to filter the array based on keys of the dictionaries using NSPredicate. I have been doing something like this:

NSString *predicateString = [NSString stringWithFormat:@"%@ == '%@'", key, value];
NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateString];
NSArray *filteredResults = [allResultsArray filteredArrayUsingPredicate:predicate];

如果传入的密钥是单字,则可以正常工作:颜色,名称,年龄。但如果密钥是多字的,它就不起作用,例如:人物年龄,人名。

This works fine if they key passed in is one-word: Color, Name, Age. But it doesn't work if the key is multi-word, like: Person Age, Person Name.

基本上,任何包含空格的键都不起作用。我已经尝试在字符串中的键周围放置单引号,就像它们在值侧完成但是也没有用。也试过双引号,但无济于事。

Basically, any key that contains a space, it doesn't work. I have tried putting single quotes around the key in the string, just like they are done on the value side but that didn't work either. Also tried double quotes, but to no avail.

请就此提出建议。在此先感谢。

Please advise on this. Thanks in advance.

推荐答案

使用动态密钥时,应使用%K 令牌而不是%@ 。您也不希望值标记周围的引号。它们将使您的谓词测试与文字字符串 @%@的相等性,而不是

When using a dynamic key, you should use the %K token instead of %@. You also don't want the quotes around the value token. They will cause your predicate to test for equality against the literal string @"%@" instead of against value.

NSString *predicateString = [NSString stringWithFormat:@"%K == %@", key, value];

这是在谓词格式字符串语法指南

编辑:正如Anum Amin指出的那样, + [NSString stringWithFormat:] doesn' t处理谓词格式。你想要 [NSPredicate predicateWithFormat:@%K ==%@,键,值]

As Anum Amin points out, +[NSString stringWithFormat:] doesn't handle predicate formats. You want [NSPredicate predicateWithFormat:@"%K == %@", key, value] instead.

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

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