在 Apple 的一个代码示例中,他们给出了一个搜索示例:
for (Person *person in personsOfInterest)
{
NSComparisonResult nameResult = [person.name compare:searchText
options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch)
range:NSMakeRange(0, [searchText length])];
if (nameResult == NSOrderedSame)
{
[self.filteredListContent addObject:person];
}
}
不幸的是,此搜索只会匹配开头的文本。如果您搜索“John”,它将匹配“John Smith”和“Johnny Rotten”,但不会匹配“Peach John”或“The John”。
有什么方法可以更改它以便在名称中的任何位置找到搜索文本?谢谢。
最佳答案
尝试使用 rangeOfString:options:
代替:
for (Person *person in personsOfInterest) {
NSRange r = [person.name rangeOfString:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch)];
if (r.location != NSNotFound)
{
[self.filteredListContent addObject:person];
}
}
另一种实现此目的的方法是使用 NSPredicate:
NSPredicate *namePredicate = [NSPredicate predicateWithFormat:@"name CONTAINS[cd] %@", searchText];
//the c and d options are for case and diacritic insensitivity
//now you have to do some dancing, because it looks like self.filteredListContent is an NSMutableArray:
self.filteredListContent = [[[personsOfInterest filteredArrayUsingPredicate:namePredicate] mutableCopy] autorelease];
//OR YOU CAN DO THIS:
[self.filteredListContent addObjectsFromArray:[personsOfInterest filteredArrayUsingPredicate:namePredicate]];
关于iphone - 搜索只匹配开头的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1526221/