Hive7
Hive7

Reputation: 3675

UISearchBar crashing when implementing text

I have an app with a tableview which you can add and delete items though when I tried to implement a search bar it crashes whenever I type one letter. Here is the code that I am using:

- (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];
}

This works fine though when you type a letter which has a patient in then it breaks at this line:

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

Here is the code in context:

- (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;
}

And returns this error

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

If you want any more code then ask.

Thanks in advance

Upvotes: 0

Views: 395

Answers (1)

dulacp
dulacp

Reputation: 1206

You are iterating on the collection patients that seems to contain Patient instances and not NSString instances. So I would do something like :

- (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];
}

Upvotes: 1

Related Questions