1

現在、テーブルに表示される DB のデータを使用して、UISearchBar の検索機能をコーディングしています。検索結果を把握して に保存しますNSMutableArray *searchResults。これがどのように見えるかです:

- (void) searchGrapesTableView {
    [searchResult removeAllObjects];
    numSearchWines=0;
    for (NSString *str in listOfWines)
    {
        NSRange titleResultsRange = [str rangeOfString:searchBar.text options:NSCaseInsensitiveSearch];
        if (titleResultsRange.length > 0) {
            [searchResult addObject:str];
            numSearchWines++;
        }
    }
}

listOfWinesまた、検索可能なすべての名前のリストを含む NSMutableArray です。理想的には、一致する値を持つオブジェクトのインデックスを決定し、listOfWinesそれを別の NSMutableArray に追加して、後で非常に簡単にアクセスできるようにしたいと考えています。たとえば、後でこの検索データを使用して表のセルを表示すると、次のコードが表示されます。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"wineCell"];
    //determine how many to add to get the grape ID
    NSInteger grapeID=0;
    for (int i=0; i<indexPath.section; i++) {
        grapeID += [self.tableView numberOfRowsInSection:i];
    }

    Wines *currentWine;
    if (isSearchOn) {
        NSString *cellValue = [searchResult objectAtIndex:(grapeID+indexPath.row)];
        NSInteger index = 0;
        index = [listOfWines indexOfObject:cellValue];
        currentWine = [allWines objectAtIndex:(index)];
    }

    else {
        currentWine = [allWines objectAtIndex:(grapeID+indexPath.row)];
    }

    cell.textLabel.text = currentWine.name;
    return cell;
}

listOfWines残念ながら、 (およびその後に)に重複するエントリがある場合、これは機能しませんsearchResult。そのため、たとえば という名前の NSMutableArray にインデックスを含めると、次のようなことができるようになると非常に便利ですsearchResultID

NSInteger theResultID = [searchResultID objectAtIndex:(grapeID+indexPath.row)];
currentWine = [allWines objectAtIndex:theResultID];
4

1 に答える 1

5

これは、indexesOfObjectsPassingTest: の仕事のように思えます。NSArray ドキュメントで確認してください。次のように使用します。

NSIndexSet  *indxs = [allWines indexesOfObjectsPassingTest: ^BOOL(NSString *obj, NSUInteger idx, BOOL *stop) {
        return [obj isEqualToString:searchBar.text]];
    }];

したがって、これは allWines のすべての値をループし (オブジェクトは文字列であると想定しています)、検索文字列に一致するすべてのインデックスを返し、見つかったインデックスを含むインデックス セットを返します。

于 2012-07-26T17:28:35.780 に答える