2

我需要一些帮助来搜索/过滤核心数据实体。结果数组返回 Null..

我有一个带有搜索栏、控制器和表格视图的根视图。此视图正常显示。

我正在调用 UISearchBarDelegate 和 UISearchDisplayDelegate。

我有一个可变数组(searchResults)。

我的搜索代码如下:

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

并且单元配置代码是:

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

我必须做一些愚蠢的事情,因为 searchResults 数组似乎为空。我会很感激任何建议。

4

1 回答 1

1

您只是忘记分配/初始化searchResults数组。

;-)

于 2012-11-20T19:33:11.153 回答