Bit*_*ttu 12 iphone nsdictionary nsarray nspredicate ios
我有一个NSDray的NSDictionary对象.我想使用NSPredicate根据字典的键过滤数组.我一直在做这样的事情:
NSString *predicateString = [NSString stringWithFormat:@"%@ == '%@'", key, value];
NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateString];
NSArray *filteredResults = [allResultsArray filteredArrayUsingPredicate:predicate];
Run Code Online (Sandbox Code Playgroud)
如果传入的密钥是单字,则可以正常工作:颜色,名称,年龄.但如果密钥是多字的,它就不起作用,例如:人物年龄,人名.
基本上,任何包含空格的键,它都不起作用.我已经尝试在字符串中的键周围放置单引号,就像它们在值侧完成但是也没有用.也试过双引号,但无济于事.
请告知此事.提前致谢.
Nig*_*ury 23
对我来说,凯文的答案没有用.我用了:
NSPredicate *predicateString = [NSPredicate predicateWithFormat:@"%K contains[cd] %@", keySelected, text];//keySelected is NSString itself
NSLog(@"predicate %@",predicateString);
filteredArray = [NSMutableArray arrayWithArray:[YourArrayNeedToFilter filteredArrayUsingPredicate:predicateString]];
Run Code Online (Sandbox Code Playgroud)
Lil*_*ard 16
使用动态密钥时,应使用%K令牌而不是%@.您也不希望值标记周围的引号.它们将使您的谓词测试与文字字符串的平等@"%@"而不是反对value.
NSString *predicateString = [NSString stringWithFormat:@"%K == %@", key, value];
Run Code Online (Sandbox Code Playgroud)
这在Predicate Format String Syntax指南中有记录.
编辑:正如Anum Amin指出的那样,+[NSString stringWithFormat:]不处理谓词格式.你想要的[NSPredicate predicateWithFormat:@"%K == %@", key, value].
| 归档时间: |
|
| 查看次数: |
16092 次 |
| 最近记录: |