繁体   English   中英

搜索仅在开头匹配单词

[英]Search is only matching words at the beginning

在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]];

-[NSString rangeOfString:options:]和朋友是你想要的。 它返回:

NSRange结构在第一次出现aString接收器中的位置和长度,以掩码中的选项为模。如果找不到aString或为空( @""{NSNotFound, 0}则返回{NSNotFound, 0}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM