在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”。
有没有办法改变它,以便在名称的任何地方找到搜索文本?感谢。
答案 0 :(得分:6)
请尝试使用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]];
答案 1 :(得分:1)
-[NSString rangeOfString:options:]
朋友就是你想要的。它返回:
“
NSRange
结构,在第一次出现aString
的接收器中给出位置和长度,以掩码中的选项为模。如果{NSNotFound, 0}
不是,则返回aString
发现或为空(@""
)。“