【问题标题】:How to concatenate two column values and compare in ios如何连接两列值并在ios中进行比较
【发布时间】:2015-03-16 11:42:10
【问题描述】:

在我的实体联系人中,我有两列名为 firstName 和 lastName。我想在我的数据库中搜索用户输入的名称。

例如:如果用户只输入“William”,我可以在名字或姓氏中搜索它的存在并显示结果。 如果用户输入“William Smith”,那么我想从 DB 中获取名字和姓氏,并将其与搜索文本进行比较。

为此,我想使用比较 3 个条件的 NSPredicate:

firstName contains the search text OR
lastName contains the search text OR
firstName+lastName contains the search text.

我为此使用了以下谓词:

NSString *strSearchType = @"(%@ CONTAINS[cd] '%@' OR %@ CONTAINS[cd] '%@' OR (%@ || %@ CONTAINS[cd] '%@')";

我知道“||”是连接运算符。

但它给了我以下例外:

  *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "(firstName CONTAINS[cd] 'rus' OR lastName CONTAINS[cd] 'rus' OR ((firstName || lastName) CONTAINS[cd] 'rus'))"'

我做错了吗?

【问题讨论】:

  • 如果名字是“xyz”,姓氏 id 是“abc”,那么你也想显示这个搜索字符串“zab”(名字+lastneme)的条目。对吗?
  • 没有。表示如果 iuser 输入 "xyz abc" ,那么我想显示结果

标签: ios objective-c


【解决方案1】:

您可以尝试以下操作:

firstName contains the search text OR
lastName contains the search text OR
(search text contains the firstName AND search text contains the lastName).

【讨论】:

    【解决方案2】:
       NSString* stringA=nil;     NSString* stringB=nil; 
    
    // this would give array of string separated by space
     NSArray *searchStrArray = [searchString componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@" "]];
    
       if (searchStrArray.count>0) {
            stringA=[searchStrArray objectAtIndex:0];
        }
        if (searchStrArray.count>1) {
            stringB=[searchStrArray objectAtIndex:1];
        }
    
    NSPredicate* predicateA= [NSPredicate predicateWithFormat:@“firstName CONTAINS[c] %@ OR lastName CONTAINS[c] %@",stringA , stringA];
    
    NSPredicate* resultPredicate=predicateA;
    
    if(stringB){
    NSPredicate* predicateB= [NSPredicate predicateWithFormat:@“firstName CONTAINS[c] %@ OR lastName CONTAINS[c] %@",stringB , stringB];
    
                resultPredicate=[NSCompoundPredicate andPredicateWithSubpredicates:[NSArray arrayWithObjects:resultPredicate,predicateB, nil]];
    
    }
    

    【讨论】:

      猜你喜欢
      • 2014-07-30
      • 1970-01-01
      • 1970-01-01
      • 2013-08-18
      • 1970-01-01
      • 2014-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多