2

请指导我正确的方式。

我实现了这段代码来获取我的对象:

- (NSFetchedResultsController *)fetchedResultsController {
    if (_fetchedResultsController != nil) {
        return _fetchedResultsController;
    }

    NSPredicate *predicate = nil;

    if (self.selectedCategory)
    {
        predicate = [NSPredicate predicateWithFormat:@"ANY category_ids.category_id == %@", self.selectedCategory];
    }

    _fetchedResultsController = [EyeArtist fetchAllGroupedBy:nil withPredicate:predicate sortedBy:@"artist_id" ascending:NO delegate:self];

    return _fetchedResultsController;
}

因此,当应用程序第一次运行时,没有谓词的 fetch 工作,所以第二次我需要使用谓词进行新的 fetch。

我点击按钮并设置字符串 self.selectedCategory,但我不知道如何从 - (NSFetchedResultsController *)fetchedResultsController; 重新获取数据

所以我想它必须像对 fetchedResultsController 实例执行新请求一样。

4

2 回答 2

5

更改搜索条件后,您必须将实例变量设置self.fetchedResultsControllernil,以便下一次调用“lazy getter”函数会使用更改的谓词创建一个新的 FRC。像这样的东西:

self.fetchedResultsController = nil;
[self.fetchedResultsController performFetch:&error];
[self.tableView reloadData];
于 2013-11-11T12:17:44.023 回答
0

这是我用于获取控制器需要属性的模式:

- (void)setSelectedCategory:(id)selectedCategory{
    if(selectedCategory == _selectedCategory){
         return _selectedCategory
    }
    _selectedCategory = selectedCategory;
    self.fetchedResultsController = nil;
    if(self.isViewLoaded){
        [self.tableView reloadData]; // but better to put this in an update views method that you can also call from viewDidLoad.
    }
}

- (NSFetchedResultsController *)fetchedResultsController {
    if (_fetchedResultsController != nil) {
        return _fetchedResultsController;
    }
    id selectedCategory = self.selectedCategory;
    // Only need this if a category is required.
    if(!selectedCategory){
        return nil;
    }
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY category_ids.category_id == %@", selectedCategory];
    _fetchedResultsController = [EyeArtist fetchAllGroupedBy:nil withPredicate:predicate sortedBy:@"artist_id" ascending:NO delegate:self];
    return _fetchedResultsController;
}
于 2018-09-09T14:51:24.267 回答