Search code examples
iphonecore-datanspredicateuisearchdisplaycontroller

filteredArrayUsingPredicate array not retained


I have a core data database and each row is shown in a table.

I have a search controller to enable the user to search by first or last name.

When i get results from 'filteredArrayUsingPredicate' i reload the search controller table and all works fine. The table shows the filtered results.

When it comes to select a result, the results array is empty and subsequently crashes due to [array atIndex:index path.row] out of bounds. The array is empty making me think it has been released.

This code works perfectly on another view. i have tried re writing and clean and build and still happening- any ideas?

Below is my code

@property(nonatomic,retain) NSArray* cachedSearchResults;

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{


    NSPredicate * predicate =  [NSPredicate predicateWithFormat:@"first_name contains[cd] %@ || last_name contains[cd] %@",searchText, searchText];
    self.cachedSearchResults = [[self.cachedResults filteredArrayUsingPredicate:predicate]retain];
;
    [searchController.searchResultsTableView reloadData];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

PupilManagedObject* selected = nil;
if(tableView == table){
    selected = [cachedResults objectAtIndex:indexPath.row];
}else{
    selected = [self.cachedSearchResults objectAtIndex:indexPath.row]; //array is empty at this point
}
}

Solution

  • I found the issue was the search controller was dismissed before i made use of the data in the array. odd but changing the order of my code worked