过滤字典数组时无法解析格式字符串?
Posted
技术标签:
【中文标题】过滤字典数组时无法解析格式字符串?【英文标题】:Unable to parse the format string while filtering array of dictionaries? 【发布时间】:2014-10-02 17:37:02 【问题描述】:我有一个字典数组如下
<__NSArrayI 0x10053e7c0>(
busType = "A/C SLEEPER";
fare = 700;
,
busType = "Volvo A/C B9R Multi-Axle Semi Sleeper";
fare = 500;
,
busType = "2+1 Hi-Tech Non A/c";
fare = 500;
,
busType = "Hitech Sleeper Cum Seater";
fare = 1500;
,
busType = "Hi-Tech Non A/c";
fare = 900;
,
busType = "Mercedes Benz Multi Axle";
fare = 1700;
)
现在我想过滤这个数组,考虑到 busType
键的值,即 A/C 或 Non A/c 加上 SLEEPER。所以我将这些值设置在两个 NSString
中以形成一个谓词,如下所示。
-(void)applyFilter:(UIButton *)sender
if (ac_Value.length>1&&sleeper_Value.length>1)
NSString *dictionaryKey = @"busType";
NSString *predicateString1 = ac_Value; // Set this NSString as A/C or Non A/c
NSString *predicateString2 = sleeper_Value; //Set this NSString as Sleeper or Non/Sleeper
NSPredicate* predicate = [NSPredicate predicateWithFormat:@"%K CONTAINS[cd] %@ %@",dictionaryKey,predicateString1,predicateString2];
NSArray *filteredArray = [busArray filteredArrayUsingPredicate:predicate];
NSLog(@"filtered array : %@", filteredArray);
但是,我一直无法通过谓词形成部分,这会给出如下错误。感谢任何帮助。
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "%K CONTAINS[cd] %@ %@"'
【问题讨论】:
【参考方案1】:如果我理解正确,您可能希望您的谓词如下所示:
[NSPredicate predicateWithFormat:@"%K CONTAINS[cd] %@ AND %K CONTAINS[cd] %@",dictionaryKey,predicateString1,dictionaryKey,predicateString2];
或者,如果键始终是 busType,您可以将其缩短为:
[NSPredicate predicateWithFormat:@"busType CONTAINS[cd] %@ AND busType CONTAINS[cd] %@",predicateString1,predicateString2];
但是,将 ac_Value 设置为“A/C”将匹配包含“A/C”和“Non A/c”的值。将 [cd] 更改为 [d] 以创建区分大小写/不区分变音的过滤器。
【讨论】:
好的...谢谢你的帮助以上是关于过滤字典数组时无法解析格式字符串?的主要内容,如果未能解决你的问题,请参考以下文章