目前,我正在使用表中显示的数据库中的数据对 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];