我知道其他人已经发布了同样的问题,但我无法得到解决问题的任何答案。我收到以下错误:
An instance of NSFetchedResultsController requires a non-nil fetchRequest and managedObjectContext
我已经加入了我的appdelegate.m:
WorkoutExercisesTVC *workoutExercisesTVC;
workoutExercisesTVC.managedObjectContext = self.managedObjectContext;
workoutExercisesTVC.fetchedResultsController = self.fetchedResultsController;
我的表视图中有控制器类:
#import "WorkoutExercisesTVC.h"
@implementation WorkoutExercisesTVC
@synthesize fetchedResultsController = __fetchedResultsController;
@synthesize managedObjectContext = __managedObjectContext;
- (void)setupFetchedResultsController
{
// 1 - Decide what Entity you want
NSString *entityName = @"WorkoutExercise"; // Put your entity name here
NSLog(@"Setting up a Fetched Results Controller for the Entity named %@", entityName);
// 2 - Request that Entity
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:entityName];
// 3 - Filter it if you want
//request.predicate = [NSPredicate predicateWithFormat:@"enity.name = Blah"];
// 4 - Sort it if you want
request.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"order"
ascending:YES
selector:@selector(localizedCaseInsensitiveCompare:)]];
// 5 - Fetch it
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
managedObjectContext:self.managedObjectContext
sectionNameKeyPath:nil
cacheName:nil];
[self performFetch];
}
我的错误发生在步骤5中的setupFetchedResultsController方法中(获取它)。
如果有人可以帮助我获取self.managedObjectContext,那么它将不再为null。让我知道您可能需要的其他信息!提前谢谢。
答案 0 :(得分:0)
为什么不遵循苹果样本中熟悉的懒惰实例化模式?
-(NSFetchedResultsController*)fetchedResultsController {
if (_fetchedResultsController) {
return _fetchedResultsController;
}
// set your fetch request, entity, predicate, sort descriptors etc.
NSFetchedResultsController *aController = [[NSFetchedResultsController alloc]
initWithFetchRequest:request
managedObjectContext:self.managedObjectContext
sectionNameKeyPath:nil
cacheName:nil];
NSError *error;
aController.delegate = self;
[aController performFetch:&error]
_fetchedResultsController = aController;
return aController;
}
当您需要刷新表格视图时(如果实施NSFetchedResultsControllerDelegate
方法则不需要):
[self.fetchedResultsController performFetch:nil];
[self.tableView reloadData];
最后,设置断点并检查托管对象上下文是否为零 - 也许您没有从代理中正确检索它。