目前,我正在使用来自显示在表格中的数据库的数据来编写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
)中有重复的条目,则此功能无效。这就是为什么它们的索引也很有用,例如,一个名为searchResultID
的NSMutableArray,这样我就可以这样做:
NSInteger theResultID = [searchResultID objectAtIndex:(grapeID+indexPath.row)];
currentWine = [allWines objectAtIndex:theResultID];
答案 0 :(得分:5)
这听起来像是indexOfObjectsPassingTest:的工作。您应该在NSArray文档中查看它。你使用它是这样的:
NSIndexSet *indxs = [allWines indexesOfObjectsPassingTest: ^BOOL(NSString *obj, NSUInteger idx, BOOL *stop) {
return [obj isEqualToString:searchBar.text]];
}];
因此,这将循环遍历allWines中的所有值(我假设对象是字符串)并返回与搜索字符串匹配的任何索引,为您提供索引集,其中包含找到的任何索引。