过滤字典数组时无法解析格式字符串?

时间:2014-10-02 17:37:02

标签: ios objective-c nsarray nsdictionary nspredicate

我有一系列字典,如下所示

  <__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或非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 个答案:

答案 0 :(得分: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设置为&#34; A / C&#34;将匹配包含&#34; A / C&#34;和&#34;非A / c&#34;。将[cd]更改为[d]以创建区分大小写/变音不敏感的过滤器。