NSManagedObjectContextDidSaveNotification not triggered in iOS 7

余生颓废 提交于 2019-12-11 21:12:04

问题


I have a situation where I make some changes to the properties of a NSManagedObject in main thread. It belongs to the main ManagedObjectContext of the app.

My app does has threading enabled which downloads data, each thread has it's own ManagedObjectContext created from the most recent state of a single PersistentStore throughout the application.

I am implementing NSManagedObjectContextDidSaveNotification so that any changes in the MOC is merged back to the main thread's MOC too. Below is the code for it:

- (void)backgroundMOCDidSave:(NSNotification*)notification
{
    // Probable fix for: http://stackoverflow.com/questions/3446983/collection-was-mutated-while-being-enumerated-on-executefetchrequest
    if (![NSThread isMainThread])
    {
        [self performSelectorOnMainThread:@selector(backgroundMOCDidSave:) withObject:notification waitUntilDone:YES];
        return;
    }

    // We merge the background moc changes in the main moc
    [self.managedObjectContext mergeChangesFromContextDidSaveNotification:notification];
}

Registering for this notification:

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(backgroundMOCDidSave:)
                                                     name:NSManagedObjectContextDidSaveNotification
                                                   object:nil];

Strange things happen in iOS 7 though. I am accessing a NSManagedObject which is created from the main MOC:

  • When I modify a property of the ManagedObject which belongs to main MOC (main thread) and perform a -save the -backgroundMOCDidSave: call is not triggered
  • When I do not modify any property of the ManagedObject and just perform a -save operation on its MOC the notification is triggered

The same code is working perfectly well in iOS 6. Irrespective of whether any changes is done on the ManagedObject or not, when a -save call is triggered on it's MOC the notification NSManagedObjectContextDidSaveNotification gets triggered.

Anyone faced this problem before?


回答1:


For now I've noticed one thing that's wrong, but I'm not sure it's causing your error. NSManagedObjectContextDidSaveNotification is sent on the thread on which MOC that calls save is running. But merging should be made on the thread MOC merging changes is running on. In your case it works fine if changes are merged from the background to the main MOC, but not the other way around.



来源:https://stackoverflow.com/questions/19219340/nsmanagedobjectcontextdidsavenotification-not-triggered-in-ios-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!