1

我知道其他人已经发布了同样的问题,但我无法得到任何答案来解决我的问题。我收到以下错误:

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 使其不再为空,将不胜感激。让我知道您可能需要的其他信息!提前致谢。

4

1 回答 1

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];

最后,设置一个断点并检查托管对象上下文是否为 nil - 也许您没有从您的委托中正确检索它。

于 2013-09-12T13:59:34.687 回答