我有一个带有tableview的应用程序,您可以添加和删除项目,但是当我尝试实现搜索栏时,只要我键入一个字母就会崩溃。这是我正在使用的代码:
- (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
如果您想要更多代码,请询问。
提前致谢
答案 0 :(得分:1)
您正在迭代似乎包含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];
}