1

特定の文字で始まるすべての名前を検索したい、つまり、検索バーに 1 文字を入力すると、その文字で始まるすべての名前が表示されますが、残念ながら、この文字を含む名前も表示されます。検索バーに入力した特定の文字で始まる名前。解決策を教えてください。

 - (void)searchBar:(UISearchBar *)searchBars textDidChange:(NSString *)search
 {

 if(search.length == 0)
 {
    isFiltered = FALSE;
 } 
 else{

    isFiltered=true;
    itemData =[[NSMutableArray alloc] init];

    for (Item *itemsearch in listOfItemForStock) {

        NSString *stringId = [NSString stringWithFormat:@"%i",itemsearch.iditem];
        NSString *stringName = [NSString stringWithFormat:@"%@",itemsearch.name];
        NSRange idRange = [stringId rangeOfString:search options:(NSCaseInsensitiveSearch)];
        NSRange nameRange = [stringName rangeOfString:search options:(NSCaseInsensitiveSearch)];

        if(idRange.location!=NSNotFound || nameRange.location != NSNotFound){

            [self.itemData addObject:itemsearch];
        }
    }
}    

[self.tableView reloadData];

}

4

2 に答える 2

2

名前チェックを接頭辞チェックに変更します。nameRange 変数を、stringName が検索文字列で始まるかどうかのみを示す BOOL に置き換えます...

/// ...
BOOL nameMatches = [[stringName lowercaseString] hasPrefix:[search lowercaseString]];

if(idRange.location!=NSNotFound || nameMatches){
    //..
于 2012-09-11T02:49:35.193 に答える
0

if(idRange.location!= NSNotFound || nameRange.location!= NSNotFound){

            NSComparisonResult result = [itemsearch.name compare:search options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [search length])];
            NSComparisonResult resultId = [[NSString stringWithFormat:@"%i",itemsearch.iditem ] compare:search options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [search length])];

            if (result == NSOrderedSame || resultId == NSOrderedSame){
                [self.itemData addObject:itemsearch];
            }
        }
于 2012-09-11T02:43:00.357 に答える