搜索只是开头的匹配单词 [英] Search is only matching words at the beginning

查看:169
本文介绍了搜索只是开头的匹配单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Apple的一个代码示例中,他们给出了一个搜索示例:

In one of the code examples from Apple, they give an example of searching:

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。

Unfortunately, this search will only match the text at the start. If you search for "John", it will match "John Smith" and "Johnny Rotten" but not "Peach John" or "The John".

有什么方法可以更改它,以便在名称的任何位置找到搜索文本?

Is there any way to change it so it finds the search text anywhere in the name? Thanks.

推荐答案

请改用 rangeOfString:options: p>

Try using rangeOfString:options: instead:

for (Person *person in personsOfInterest) {
    NSRange r = [person.name rangeOfString:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch)];

    if (r.location != NSNotFound)
    {
            [self.filteredListContent addObject:person];
    }
}

另一种可以实现这一点的方法是使用NSPredicate :

Another way you could accomplish this is by using an 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]];

这篇关于搜索只是开头的匹配单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆