问题描述
我有一个情况,我对主线程中的NSManagedObject的属性进行一些更改。它属于应用程序的主ManagedObjectContext。
我的应用程序启用了线程下载数据,每个线程都有自己的ManagedObjectContext从单个最近的状态创建PersistentStore。
我正在实现 / p>
现在我注意到一件事情是错误的,但我不确定它是否导致你的错误。 NSManagedObjectContextDidSaveNotification 在调用 save 的MOC正在运行的线程上发送。但是合并应该在线程MOC合并更改正在运行。在你的情况下,如果更改从背景合并到主要MOC,但没有反过来工作正常。
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?
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.
这篇关于NSManagedObjectContextDidSaveNotification在iOS 7中未触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!