代码之家  ›  专栏  ›  技术社区  ›  nevan king

搜索只在开头匹配单词

  •  4
  • nevan king  · 技术社区  · 15 年前

    在苹果公司的一个代码示例中,他们给出了一个搜索示例:

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

    不幸的是,此搜索将只匹配开始时的文本。如果你搜索“约翰”,它将匹配“约翰史密斯”和“约翰尼腐烂”,但不是“桃子约翰”或“约翰”。

    是否有任何方法可以更改它以便在名称中的任何位置找到搜索文本?谢谢。

    2 回复  |  直到 15 年前
        1
  •  6
  •   Dave DeLong    15 年前

    试用使用 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]];
    
        2
  •  1
  •   Quinn Taylor    15 年前

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

    “安” NSRange 结构,给出第一次出现的接收器中的位置和长度 aString ,对mask中的选项进行模块化。退换商品 {NSNotFound, 0} 如果 收敛的 未找到或为空( @""