请指导我正确的方式。
我实现了这段代码来获取我的对象:
- (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;
}
因此,当app在第一次运行时,fetch在没有谓词的情况下工作,所以第二次我需要使用谓词进行新的提取。
我点击按钮并设置字符串self.selectedCategory,但我不知道如何从 - (NSFetchedResultsController *)fetchedResultsController;
重新获取数据所以我认为它必须像对fetchedResultsController实例执行新请求。
答案 0 :(得分:5)
更改搜索条件后,您必须将实例变量self.fetchedResultsController
设置为nil
,
以便下一次调用“lazy getter”函数创建一个新的FRC
改变了谓词。像这样:
self.fetchedResultsController = nil;
[self.fetchedResultsController performFetch:&error];
[self.tableView reloadData];
答案 1 :(得分: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;
}