我有一个 UIViewController,它从 web 服务中获取 JSON 数据并将其映射到一个对象(称为 Post)。在我的 viewDidLoad 中,我能够从 self.fetchedResultsController.fetchedObjects 获取这些数据。我的问题是我试图在子视图控制器中做同样的事情,而 fetchedResultsController performFetch 不会产生错误,但是 fetchedObjects 是空的。
我像这样传递 managedObjectContext :
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
[super prepareForSegue:segue sender:sender];
if ([segue.identifier isEqualToString:@"PostsList"] == YES) {
PostViewController *postsController = [segue destinationViewController];
postsController.managedObjectContext = self.managedObjectContext;
}
}
在我的故事板中,我使用 PostsList 作为标识符进行了嵌入 segue。在我的 viewDidLoad 我有以下内容:
- (void)viewDidLoad
{
[super viewDidLoad];
[[RKObjectManager sharedManager] getObjectsAtPath:@"/flog/post" parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
NSLog(@"Fetched count %d",[self.fetchedResultsController.fetchedObjects count]);
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
NSLog(@"fail!");
}];
}
我的 fetchedResultsController 看起来像:
- (NSFetchedResultsController *)fetchedResultsController
{
if (_fetchedResultsController != nil) {
return _fetchedResultsController;
}
NSLog(@"The managedObjectContext %@", self.managedObjectContext);
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Post" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
[fetchRequest setFetchBatchSize:20];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"created" ascending:NO];
NSArray *sortDescriptors = @[sortDescriptor];
[fetchRequest setSortDescriptors:sortDescriptors];
NSLog(@"fetchRequest appears ok %@", fetchRequest );
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"Post"];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
NSLog(@"The fetchedResultsController %@", aFetchedResultsController );
NSError *error = nil;
if (![self.fetchedResultsController performFetch:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
NSLog(@"post fetched %@", self.fetchedResultsController.fetchedObjects );
return _fetchedResultsController;
}
我已经将行为与父控制器进行了比较,看不出有任何区别。任何帮助或调试提示将不胜感激。谢谢阅读。