【问题标题】:Search filtered array indexPath is not correct搜索过滤后的数组 indexPath 不正确
【发布时间】:2013-08-25 12:14:53
【问题描述】:

我有一个应用程序,当您使用搜索栏时,它会根据您输入的内容过滤患者,但当您单击一行时,它总是在下一个 nib 文件中显示相同的数据。我知道这是因为 indexPath 随着单元格的顺序和数量的变化而变化,但是有没有办法让它转到正确的?

索引路径代码:

- (void)tableView:(UITableView *)tv didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    LSAppDelegate *delegate = (LSAppDelegate *)[[UIApplication sharedApplication] delegate];
    PatientController *patient = [[PatientController alloc] initWithIndexPath:indexPath];
    [delegate.navController pushViewController:patient animated:YES];
    [tv deselectRowAtIndexPath:indexPath animated:YES];
}

搜索代码:

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    if (searchText.length == 0) {
        isFiltered = NO;
    } else {
        isFiltered = YES;

        filteredPatients = [[NSMutableArray alloc] init];

        for (Patient *patient in patients) {
            NSRange patientNameRange = [[patient.patientName substringToIndex:1] rangeOfString:searchText options:NSCaseInsensitiveSearch];

            if (patientNameRange.location != NSNotFound) {
                [filteredPatients addObject:[NSString stringWithFormat:@"%@ %@", patient.patientName, patient.patientSurname]];
            }
        }
    }
    [self.tableView reloadData];
}

【问题讨论】:

  • 你的问题有点含糊。您能否详细说明并显示您正在使用的索引路径的一些代码?
  • @XCodeMonkey 已添加代码

标签: iphone ios objective-c uitableview uisearchbar


【解决方案1】:

完成过滤后,您需要刷新 UI(可能是表格视图)。现在应该从过滤结果中获取行信息 - 这包括行数、单元格内容和单元格选择源数据。如果您在搜索后刷新并使用正确的数据源,那么一切都会匹配。


不要传递indexPath。它是您的表视图控制器的私有内部状态(以及如何使用它取决于关于搜索是否正在进行的私有状态)。因此,获取所选行的患者对象并传递它。比如:

Patient *selectedPatient = nil;

if (!isFiltered) {
    selectedPatient = patients[indexPath.row];
} else {
    selectedPatient = filteredPatients[indexPath.row];
}


PatientController *patientController = [[PatientController alloc] initWithIndexPath:indexPath];
patientController.patient = selectedPatient;

这一切都在didSelectRowAtIndexPath:。在PatientController 上,您需要从.h 文件中删除indexPath 属性并将其替换为(或公开)您的属性,以获取控制器当前由于indexPath 而获得的patient。然后您可以从PatientController 中删除有关indexPath 的所有内容,因为您已经拥有patient 实例。

【讨论】:

  • PatientController 如何使用indexPath
  • 它声明一个像这样的变量:NSObject *object = [array objectAtIndex:index.row]; 然后像这样使用对象:text1.text = object.name;
  • 好的,那么代码中的array 和问题代码中的filteredPatients 之间的联系是什么?
  • 你是说如果数组是过滤后的数组,我应该传递一个不同的变量吗?
  • 好吧,我同意@atomk 的观点,你根本不应该通过indexPath。应该可以通过传递它来使其工作,但你需要教PatientController 比它已经知道的更多(看起来太多了)。
【解决方案2】:

您的错误出现在您对initWithIndexPath 的实现中,尽管我不知道您在哪里发布,因为您没有发布它。

您需要使用索引路径通过查询用于填充当前显示的表格的数据结构来获取单元格表示的数据。所以你想查询过滤的病人,但它只包含字符串。用实际的患者对象填充它,并在表格要求单元格时生成字符串。

这是一个糟糕的设计,患者视图控制器不应该知道索引路径。使用索引路径获取患者,然后将其传递给initWithPatient

另外,像这样使用应用委托是个坏主意。您可以使用self.navigationController访问包含导航控制器

【讨论】:

  • 我的应用程序几乎完成了,所以我现在不想去更改它
  • 下次再​​来。我的主要观点是,你的错误在那个 init 方法中,所以如果你需要更多帮助,你应该发布它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-21
  • 1970-01-01
  • 2020-05-30
  • 1970-01-01
  • 2020-04-01
  • 1970-01-01
相关资源
最近更新 更多