0

我有以下过滤某些结果的方法:目前它这样做:array: alpha, apple, aries, bravo

输入一个:

阿尔法苹果白羊座

l 型(现在是 al)

α

我想这样做:

新搜索:输入 p= alpha apple

下面是代码

提前谢谢你

-(void) filterResults:(NSString *)searchText{
    NSMutableArray *test = [NSMutableArray arrayWithArray:self.listContent];

    [self.filteredListContent removeAllObjects]; // First clear the filtered array.
        for (int i=0; i<[test count]; i++) {
            NSString *stringResult = [test objectAtIndex:i];
            NSComparisonResult result = [stringResult compare:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchText length])];

            if (result == NSOrderedSame){
                [self.filteredListContent addObject:stringResult];

            }
        }
    [self.filteredListContent sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];//sort alphabetically
    NSLog(@"filtered results = %@",self.filteredListContent);
}
4

2 回答 2

1

要在字符串中的任何位置查找字母,请将其替换:

NSComparisonResult result = [stringResult compare:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchText length])];
if (result == NSOrderedSame){
    [self.filteredListContent addObject:stringResult];
}

有了这个:

NSRange range = [stringResult rangeOfString:searchText];
if (range.location != NSNotFound) {
    [self.filteredListContent addObject:stringResult];
}

请注意,它必须按顺序查找所有字符。

如果要查找任何字符,请使用rangeOfCharacterFromSet:.

于 2012-12-17T06:11:03.740 回答
0

试试这个。

NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"SELF beginswith '%@'", searchText]];
self.filteredListContent  = [self.listContent filteredArrayUsingPredicate:predicate];

希望这对您有所帮助。

于 2012-12-17T06:36:06.273 回答