如何连接两个列值并在ios中进行比较

时间:2015-03-16 11:42:10

标签: ios objective-c

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

例如:如果用户只输入'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'))"'

我做错了吗?

2 个答案:

答案 0 :(得分:0)

您可以尝试以下操作:

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

答案 1 :(得分:0)

   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]];

}
相关问题