搜索仅在开头匹配单词

nev*_*ing 4 iphone search cocoa objective-c

在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];
    }
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,此搜索仅匹配开头的文本.如果您搜索"John",它将匹配"John Smith"和"Johnny Rotten",但不匹配"Peach John"或"The John".

有没有办法改变它,以便在名称中的任何地方找到搜索文本?谢谢.

Dav*_*ong 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];
    }
}
Run Code Online (Sandbox Code Playgroud)

另一种可以实现此目的的方法是使用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]];
Run Code Online (Sandbox Code Playgroud)