为什么我的UISearchDisplayController访问非法的单元格/ indexPath



>我有一个带有搜索栏的表格视图。最初,表视图显示所有 (10) 个项目。当我选择一个单元格时,将在导航控制器堆栈上推送一个详细信息视图,然后我可以通过点击"后退"按钮返回到表视图。只要我还没有输入搜索文本,表视图就会显示所有项目,我可以无限期地在详细信息视图和表视图之间来回切换。

当我在搜索栏中输入文本时,表格视图会使用 self.searchDisplayController.searchResultsTableView 正确更新(假设它现在只显示 8 个项目),这意味着

(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 

调用 8 次(第 0 节,第 0 行到第 7 行)。好。

然后,

我可以点击一个单元格,查看详细信息视图,然后返回到显示 8 个项目的表视图。

如果我随后在表格视图中选择一个仍然显示 8 个项目的单元格(与之前相同的单元格或不同的单元格,没关系),我再次看到详细信息视图,然后点击"返回"按钮,

(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 

为不存在的第 0 节第 8 行调用,因为searchResultsTableView仍然只显示搜索中的 8 个项目(第 0 行到第 7 行)。

我真的不明白发生了什么:

  • 搜索工作正常,
  • cellForRowAtIndexPath是用"错误"的 indexPath 调用

编辑:删除了关于混合两个表视图的假设 - 一切似乎都在正确的位置,但第 8 行仍然调用 cellForRowAtIndexPath。另请注意,它始终是第 8 行。

编辑2:这是cellForRowAtIndexPath。"Zeichen"是一个DAO,getZeichenForIndexPath:indexPath从搜索结果中返回正确的实例。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SearchResultCell" ];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"SearchResultCell"];
    }
    Zeichen *zeichen = [self getZeichenForIndexPath:indexPath];
    UIImage *img = [UIImage imageNamed:zeichen.filename];
    cell.imageView.image = img;
    cell.textLabel.text = [zeichen description];
    return cell;
}

我认为你应该控制tableView == self.searchDisplayController.searchResultsTableView.此控件也应didSelectRowAtIndexPath:方法中。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
      if(tableView == self.searchDisplayController.searchResultsTableView)
      {
             UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SearchResultCell" ];
             if (cell == nil) {
                  cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"SearchResultCell"];
             }
      }
      else
      {
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" ];
             if (cell == nil) {
                  cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
             }
      }
    return cell;
}

其他想法:如果您在情节提要或 NIB 中初始化表视图(在情节提要中设置单元格标识符),[tableView dequeueReusableCellWithIdentifier:@"SearchResultCell" forIndexPath:indexPath]用法更方便。

最新更新