如何为NSPredicate连接两个字符串,即firstname和lastname
我有一个Person
对象,它有两个NSString
属性; firstName and lastName
。 我目前正在使用像这样的NSPredicate
:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(firstName contains[cd] %@) OR (lastName contains[cd] %@)", searchText, searchText];
因此,举例来说,我正在寻找"John Smith"
这个名字。 在我的搜索栏中,如果我键入"Joh"
,那么John Smith
将作为选项出现。 这很好,但如果我输入"John Sm"
,它将变为空白。
如何在predicate
加入firstName和lastName,这样如果我搜索"John Sm"
那么John Smith
仍然会作为一个选项出现。
我希望这是有道理的。 谢谢。
编辑:为了进一步澄清,我正在使用SearchDisplayController
委托方法:
-(void)filterContentForSearchText:(NSString *)searchText scope:(NSString *)scope;
我正在使用这样的predicate
:
newArray = [personObjectArray filteredArrayUsingPredicate:predicate];
尝试这个,
NSString *text = @"John Smi"; NSString *searchText = [text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; NSArray *array = [searchText componentsSeparatedByString:@" "]; NSString *firstName = searchText; NSString *lastName = searchText; NSPredicate *predicate = nil; if ([array count] > 1) { firstName = array[0]; lastName = array[1]; predicate = [NSPredicate predicateWithFormat:@"(firstName CONTAINS[cd] %@ AND lastName CONTAINS[cd] %@) OR (firstName CONTAINS[cd] %@ AND lastName CONTAINS[cd] %@)", firstName, lastName, lastName, firstName]; } else { predicate = [NSPredicate predicateWithFormat:@"firstName CONTAINS[cd] %@ OR lastName CONTAINS[cd] %@", firstName, lastName]; } NSArray *filteredArray = [people filteredArrayUsingPredicate:predicate]; NSLog(@"%@", filteredArray);
输出:
( { firstName = John; lastName = Smith; } )
这里的文字代表搜索到的文字。 上面的优点是,即使你传递text = @"Smi Joh";
或者text = @"John ";
或text = @" smi";
或者text = @"joh smi ";
,它仍然会显示上面的输出。
您可以将字段连接到两个公共字段(firstLastName和lastFirstName)
- (NSString *)firstLastName { return [NSString stringWithFormat:@"%@ %@", self.firstName, self.lastName]; } - (NSString *)lastFirstName { return [NSString stringWithFormat:@"%@ %@", self.lastName, self.firstName]; }
然后使用’contains [cd]’过滤这些字段
[NSPredicate predicateWithFormat:@"(firstLastName contains[cd] %@) OR (lastFirstName contains[cd] %@)" , self.searchBar.text, self.searchBar.text];
上面建议的解决方案不适用于具有两个以上单词的搜索字符串。 这是swift中更全面的实现。 此解决方案还允许在记录上添加更多字段,如果您的目标是在名称,电子邮件,电话号码等之间实现全文搜索。在这种情况下,只需将NSPredicate更新为OR newField CONTAINS[cd] %@
newField OR newField CONTAINS[cd] %@
并且一定要在字符串替换列表中添加额外的$ 0。
let searchText = search.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) let words = searchText.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) let predicates = words.map { NSPredicate(format: "firstName CONTAINS[cd] %@ OR lastName CONTAINS[cd] %@", $0,$0) } let request = NSFetchRequest() request.predicate = NSCompoundPredicate(type: NSCompoundPredicateType.AndPredicateType, subpredicates: predicates)