iphone - 搜索只匹配开头的单词

标签 iphone objective-c cocoa search

在 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/

相关文章:

cocoa - 当弹出窗口位于状态栏中时,NSPopover transient

php - 适用于 iPhone 和 Android 的图形库

iphone - Xcode 未将最新资源文件复制到 iPhone

iphone - NSURLConnection 委托(delegate)方法没有被调用

ios - 如何根据声明顺序对 UITableView header 进行排序

iphone - 弃用的 TransactionReceipt

ios - UITextView 没有在 UICollectionViewCell 中启动

objective-c - 有 OSX API 可以自己绘制候选输入法吗?

ios - 如何停止对 iPhone 5S 的支持

cocoa - 如何以固定宽度获取 NSAttributedString 的高度