NSFetchedResultsController,NSManagedObjectContextDidSaveNotification和MagicalRecord的舞蹈

时间:2014-05-08 00:11:58

标签: ios core-data magicalrecord nsfetchedresultscontroller

问题:我正在收到NSManagedObjectContextDidSaveNotification通知。我正在将更改合并到我的NSFetchedResultsController的上下文中。但NSFetchedResultsController不会触发didChangeSection,didChangeObject,controllerDidChangeContent方法。

self.managedObjectContext = [NSManagedObjectContext MR_context]; //set up my own context to avoid deadlocking
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"Master"];
self.fetchedResultsController.delegate = self;
[self.managedObjectContext setStalenessInterval:0];

//listen for changes in the main context:
[[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(managedObjectContextDidSave:)
                                                     name:NSManagedObjectContextDidSaveNotification
                                                   object:[NSManagedObjectContext MR_defaultContext]];

- (void)managedObjectContextDidSave:(NSNotification *)notification {
    NSLog(@"[%@ %@] REFRESH!", THIS_FILE, THIS_METHOD); //this happens

    void (^mergeChanges) (void) = ^{
        for(NSManagedObject *object in [[notification userInfo] objectForKey:NSUpdatedObjectsKey]) {
            //this happens (a lot)
            [[self.managedObjectContext objectWithID:[object objectID]] willAccessValueForKey:nil];
        }
        [self.managedObjectContext mergeChangesFromContextDidSaveNotification:notification];
    };
    if ([NSThread isMainThread]) {
        mergeChanges();
    }
    else {
        dispatch_sync(dispatch_get_main_queue(), mergeChanges);
    }

}

所以再次,我收到通知就好了。但我的结果控制器不会更新。这是在杀我!请帮忙!

编辑:也尝试了这个:

self.fetchedResultsController = [NSManagedObject MR_fetchController:fetchRequest delegate:self useFileCache:NO groupedBy:nil inContext:[NSManagedObjectContext MR_defaultContext]];

导致同样的死锁。如果我这样做:

self.fetchedResultsController = [NSManagedObject MR_fetchController:fetchRequest delegate:self useFileCache:NO groupedBy:nil inContext:[NSManagedObjectContext MR_context]]; //note that I just changed the context

fetchedResultsController不会更新其结果。

1 个答案:

答案 0 :(得分:0)

我没有看到您要保存的环境或方式。如果您没有一直保存到持久性存储,那么defaultcontext没有获得这些更改,并且您的nsfetchedresultscontroller也不会更新。您可能需要在本地上下文与nsfrc正在使用的上下文之间建立连接,以便传播更改。