我的搜索栏有以下方法,用于搜索exerciseName
中的密钥exerciseArray
。这工作正常,但它只是将{key}添加到listOfItems
项,然后我用它来填充单元格的textLabel。我希望它也有相应的muscleName
。谁能告诉我怎么样?我想我需要将listOfItems更改为字典,还是有键?
- (void) searchTableView {
NSString *searchText = searchBar.text;
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
for (NSDictionary *dictionary in self.exerciseArray)
{
NSString *value = [dictionary objectForKey:@"exerciseName"];
[searchArray addObject:value];
}
for (NSString *sTemp in searchArray)
{
NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResultsRange.length > 0)
[listOfItems addObject:sTemp];
}
searchArray = nil;
}
当我记录exerciseArray
时:
答案 0 :(得分:2)
直接过滤exerciseArray
:
listOfItems = [exerciseArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"exerciseName contains [c] %@",searchText]];
这将返回一个只包含匹配字典的数组。
答案 1 :(得分:0)
你可以尝试两件事。
对于第二种方法,您必须将代码修改为
- (void) searchTableView {
NSString *searchText = searchBar.text;
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
for (NSDictionary *dictionary in self.exerciseArray)
{
NSString *value = [dictionary objectForKey:@"exerciseName"];
//workout alloc init
workout.exercise = [dictionary objectForKey:@"exerciseName"];
workout.muscle = [dictionary objectForKey:@"muscleName"];
[searchArray addObject:workout];
}
/*See if this is necessary to implement*/
//for (NSString *sTemp in searchArray)
//{
// NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch];
//if (titleResultsRange.length > 0)
//[listOfItems addObject:sTemp];
//}
//searchArray = nil;
}
我建议你选择第一种相当简单的方法。
如果你采用第一种方法,你可以试试这个。
- (void) searchTableView {
NSString *searchText = searchBar.text;
for (NSDictionary *dictionary in self.exerciseArray)
{
NSString *exerciseName = [dictionary objectForKey:@"exerciseName"];
NSRange titleResultsRange = [exerciseName rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResultsRange.length > 0)
[listOfItems addObject:dictionary];
}
}
- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section {
return [listOfItems count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *stringIdentifier = @"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:stringIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:stringIdentifier];
}
NSDictionary *dictionary = (NSDictionary *)[listOfItems objectAtIndex:indexPath.row];
[cell.textLabel setText:[dictionary objectForKey:@"exerciseName"]];
[cell.detailTextLabel setText:[dictionary objectForKey:@"muscleName"]];
return cell;
}