【问题标题】:+[NSPredicate predicateWithFormat] substitute reserved words+[NSPredicate predicateWithFormat] 替换保留字
【发布时间】:2011-12-19 19:17:41
【问题描述】:

是否可以将保留字(特别是 ORAND)替换为 predicateFormat

我试过了:

NSString *andOr = (isAnd ? @"AND" : @"OR");  // isAnd is a BOOL variable
NSPredicate *predicate = [NSPredicate predicateWithFormat:
                          @"firstName == %@ %K lastName == %@",
                          user.firstName, andOr, user.lastName];

但我得到了:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: 'Unable to parse the format string "firstName == %@ %K lastName == %@"

我尝试了%s(以及%S)而不是%K,但遇到了同样的异常。

我目前的工作解决方案是单独创建predicateFormat

NSString *predicateFormat = [NSString stringWithFormat:
                             @"firstName == %%@ %@ lastName == %%@", andOr]; 
NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateFormat,
                          user.firstName, user.lastName];

但是,我想知道这是否可以在不单独创建 predicateFormat 的情况下完成。

【问题讨论】:

    标签: nspredicate stringwithformat predicatewithformat


    【解决方案1】:

    是的,它可以:

    NSPredicate *firstName = [NSPredicate predicateWithFormat:@"firstName == %@", [user firstName]];
    NSPredicate *lastName = [NSPredicate predicateWithFormat:@"lastName == %@", [user lastName]];
    NSArray *subpredicates = [NSArray arrayWithObjects:firstName, lastName, nil];
    
    NSPredicate *predicate = nil;
    if (isAnd) {
      predicate = [NSCompoundPredicate andPredicateWithSubpredicates:subpredicates];
    } else {
      predicate = [NSCompoundPredicate orPredicateWithSubpredicates:subpredicates];
    }
    

    【讨论】:

      【解决方案2】:

      我正在使用搜索栏文本过滤数据。

      以下代码很简单,无需解释

      NSString *predFormat=[NSString stringWithFormat:@"FirstName CONTAINS[c] '%@' OR LastName CONTAINS[c] '%@' OR Phone CONTAINS[c] '%@'",searchValue,searchValue,searchValue] ; //喜欢

      NSPredicate *predicate = [NSPredicate predicateWithFormat:predFormat];

      NSArray *tempData = [数组过滤ArrayUsingPredicate:predicate];

      希望这对你有用.. 快乐的编码......

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-09-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多