[英]How to concatenate two column values and compare in ios
In my entity Contact, I have two columns named firstName & lastName.在我的实体联系人中,我有两列名为 firstName 和 lastName。 I want to search for a name entered by user in my DB.
我想在我的数据库中搜索用户输入的名称。
For Eg: If user enters only 'William' I can search either its present in first name or last name and show the result.例如:如果用户只输入“威廉”,我可以搜索它的名字或姓氏并显示结果。 If the user enters 'William Smith', then I want to get both first name and last name from DB and compares it with search text.
如果用户输入“William Smith”,那么我想从数据库中获取名字和姓氏,并将其与搜索文本进行比较。
For this i want to use NSPredicate that compares 3 condition:为此,我想使用比较 3 个条件的 NSPredicate:
firstName contains the search text OR
lastName contains the search text OR
firstName+lastName contains the search text.
I used the following predicate for that:我为此使用了以下谓词:
NSString *strSearchType = @"(%@ CONTAINS[cd] '%@' OR %@ CONTAINS[cd] '%@' OR (%@ || %@ CONTAINS[cd] '%@')";
I know "||"我知道“||” is the concatenate operator.
是连接运算符。
But it gives me the following exception:但它给了我以下异常:
*** 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'))"'
Am i doing anything wrong ?我做错了什么吗?
You can try following :您可以尝试以下操作:
firstName contains the search text OR
lastName contains the search text OR
(search text contains the firstName AND search text contains the lastName).
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]];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.