使用NSPredicate过滤NSDictionary对象的NSArray

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

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

这个工作正常,如果他们的钥匙传入是单词:颜色,名称,年龄。 但是,如果密钥是多字,则不起作用,如:人员年龄,人员姓名。

基本上,任何包含空格的键都不起作用。 我试图把单引号围绕string中的键,就像他们在价值方面做,但也没有工作。 也试过双引号,但无济于事。

请告知这个。 提前致谢。

使用dynamic密钥时,应使用%K标记而不是%@ 。 你也不需要价值标记周围的引号。 它们将导致您的谓词testing与文本string@"%@"相等而不是与value相等。

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

这在“ 谓词格式string语法”指南中进行了说明 。


编辑:作为Anum阿明指出, +[NSString stringWithFormat:]不处理谓词格式。 你需要[NSPredicate predicateWithFormat:@"%K == %@", key, value]来代替。

对我来说,凯文的答案没有奏效。 我用了:

 NSPredicate *predicateString = [NSPredicate predicateWithFormat:@"%K contains[cd] %@", keySelected, text];//keySelected is NSString itself NSLog(@"predicate %@",predicateString); filteredArray = [NSMutableArray arrayWithArray:[YourArrayNeedToFilter filteredArrayUsingPredicate:predicateString]];