ICL1901
ICL1901

Reputation: 7778

How to get result from Core Data search/filter?

I need some help searching / filtering a Core data entity. The results array returns Null..

I have a root view with a search bar, controller and tableview. This view shows normally.

I'm calling the UISearchBarDelegate and the UISearchDisplayDelegate.

I have a mutable array (searchResults).

My search code is as follows:

-(void) filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
    NSLog(@"%s", __FUNCTION__);
    [self.searchResults removeAllObjects];

    for (Entity *ent in [self.fetchedResultsController fetchedObjects])
    {
        if ([scope isEqualToString:@"All"] || [ent.title isEqualToString:scope])
        {
            NSRange range = [ent.title rangeOfString:searchText options:NSCaseInsensitiveSearch];

            if (range.location != NSNotFound)
            {
                NSLog(@"Adding title '%@' to searchResults as it contains  '%@'", ent.title, searchText);
                [self.searchResults addObject:ent];
            }
        }

    }
    NSLog(@"The searchResults array contains '%@'", searchResults); <<<< RETURNS NULL
}



- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    [self filterContentForSearchText:searchString scope:@"All"];
    return YES;
}

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption
{
    [self filterContentForSearchText:[self.searchDisplayController.searchBar text ]scope:@"All"];
    return YES;
}

and the cell config code is:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"MyVeryOwnCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    // Configure the cell...
    Entity *entity = nil;

    if (tableView == self.searchDisplayController.searchResultsTableView)
    {
        //NSLog(@"Configuring cell to show search results");
        entity = [self.searchResults objectAtIndex:indexPath.row];
    }
    else
    {
        //NSLog(@"Configuring cell to show normal data");
        entity = [self.fetchedResultsController objectAtIndexPath:indexPath];
    }
    cell.textLabel.text = entity.title;
    return cell;
}

I must be doing something dumb as the searchResults array appears to be null. I would appreciate any advice.

Upvotes: 2

Views: 250

Answers (1)

Matthias Bauch
Matthias Bauch

Reputation: 90117

You just forgot to alloc/init the searchResults array.

;-)

Upvotes: 1

Related Questions