UISearchBar在实现文本时崩溃



我有一个带有表视图的应用程序,您可以添加和删除项目,但当我尝试实现搜索栏时,每当我键入一个字母时,它就会崩溃。这是我正在使用的代码:

- (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 rangeOfString:searchText options:NSCaseInsensitiveSearch];
            if (patientNameRange.location != NSNotFound) {
                [filteredPatients addObject:patient];
            }
        }
    }
    [self.tableView reloadData];
}

不过,当你输入一封有病人的信时,它会在这一行中断:

cell.textLabel.text = [filteredPatients objectAtIndex:indexPath.row];

以下是上下文中的代码:

- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tv dequeueReusableCellWithIdentifier:@"cell"];
    if ( nil == cell ) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    NSLog(@"indexPath.row = %d, patients.count = %d", indexPath.row, patients.count);
    Patient *thisPatient = [patients objectAtIndex:indexPath.row];
    if (isFiltered == YES) {
        cell.textLabel.text = [filteredPatients objectAtIndex:indexPath.row];
    } else {
        cell.textLabel.text = [NSString stringWithFormat:@"%@ %@", thisPatient.patientName, thisPatient.patientSurname];
    }
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.textLabel.textColor = [UIColor blackColor];
    if (self.editing) {
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    }
    return cell;
}

并返回此错误

-[Patient isEqualToString:]: unrecognized selector sent to instance 0x756c180

如果您想要更多的代码,请询问。

提前感谢

您正在迭代集合patients,该集合似乎包含Patient实例而不是NSString实例。所以我会做一些类似的事情:

- (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.name rangeOfString:searchText options:NSCaseInsensitiveSearch];
            if (patientNameRange.location != NSNotFound) {
                [filteredPatients addObject:patient];
            }
        }
    }
    [self.tableView reloadData];
}

最新更新