現在、テーブルに表示される 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];