1

I am removing the persistentStore from a persistentStoreCoordinator at some point in my application (and loading another store) and reset my managedObjectContext. When I do that, according to the documentation, I also need to delete all references to managedObjects that have been fetched:

All the receiver's managed objects are “forgotten.” If you use this method, you should ensure that you also discard references to any managed objects fetched using the receiver,
since they will be invalid afterwards.

I would like to avoid having to go through all my fetchedResultsControllers, caches, arrays that may contain managedObjects, detail views that also store an object, etc.

Instead I'd prefer to observe if the managed object's isInserted status changes. Something like

[myObject addObserver:self
           forKeyPath:@"isInserted"
              options:0
              context:nil];

Unfortunately this doesn't seem to work.

So – how can I observe if a NSManagedObject is removed from managedObjectContext?

4

3 回答 3

3

用于NSNotificationCenter观察NSManagedObjectContextObjectsDidChangeNotification消息,然后检查deletedObjects您的NSManagedObjectContext. 有关详细信息,请参阅文档:https ://developer.apple.com/library/ios/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSManagedObjectContext_Class/NSManagedObjectContext.html#//apple_ref/occ/instm/NSManagedObjectContext/deletedObjects

于 2013-08-24T23:27:02.580 回答
0

没有内置通知或您可以观察到的更改确实可以满足您的需求。但是很容易建立自己的。当您完成删除持久存储和重置上下文的过程时,发布您自己的通知 -@"MyAppCoreDataExploded"或其他内容。在任何使用托管对象的控制器中观察此通知。当您收到该通知时,请清理所有本地引用。

于 2013-08-25T21:07:56.220 回答
0

我发现NSPersistentStoreCoordinatorStoresDidChangeNotification在我的情况下观察效果很好。它被调用了两次——第一次是删除旧的持久存储,第二次是添加新的存储。

我仍在测试这个解决方案是否比 Nicholas 建议的更适合我的案例。

于 2013-08-25T19:20:28.720 回答