我有一个tableview,它加载了一个名为self.annotationToSort的数组,并使用UISearchBar在tableview中搜索对象并更新结果。如果选择了tableview中的项目,则会显示详细视图以及相应的索引路径信息。
我遇到的问题是,当使用搜索栏时,我在搜索中得到2个结果项,单元格中的值显示正确,但是我点击结果B,我得到对象A传递给细节视图控制器。如果我点击A,我也会得到A.
以下是相关代码:
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
if ([self.annotationsToSort count] == 0) {
return 1;
} else if (tableView == self.searchDisplayController.searchResultsTableView) {
return [filteredResultsArray count];
} else {
return [self.annotationsToSort count];
}
}
#pragma mark Content Filtering
-(void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope {
[self.filteredResultsArray removeAllObjects];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(SELF.name contains[c] %@) OR (SELF.ciudad contains[c] %@)", searchText,searchText];
[self.filteredResultsArray = [NSMutableArray arrayWithArray:[self.annotationsToSort filteredArrayUsingPredicate:predicate]] retain];
}
#pragma mark - UISearchDisplayController Delegate Methods
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
[self filterContentForSearchText:searchString scope:
[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
tableType = @"FILTER";
return YES;
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption {
[self filterContentForSearchText:self.searchDisplayController.searchBar.text scope:
[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:searchOption]];
return YES;
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
NSLog(@"indexpath selected %@", indexPath);
//Check if using normal or search array
if ([tableType isEqualToString:@"FILTER"]) {
MyLocation *sendingLocation = [self.filteredResultsArray objectAtIndex:indexPath.row];
DetailViewController *destinationViewController = segue.destinationViewController;
destinationViewController.receivedLocation = sendingLocation;
NSLog(@"indexpath selected filter %@", indexPath);
} else {
MyLocation *sendingLocation = [self.annotationsToSort objectAtIndex:indexPath.row];
DetailViewController *destinationViewController = segue.destinationViewController;
destinationViewController.receivedLocation = sendingLocation;
NSLog(@"indexpath selected regular %@", indexPath);
}
}
我可以看到在过滤tableview时索引路径被记录为null。它总是返回objectAtIndex:0。
答案 0 :(得分:3)
你不应该做NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
,因为有时候你会问错误的表格视图,它会返回nil(当访问行数为零时,会返回结果)。
相反,请检查您是否已过滤,并询问相应的表视图以获取索引。