Reputation: 8457
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?
Upvotes: 1
Views: 1393
Reputation: 70946
There's no built-in notification or change you can observe that really does what you want. But it's easy to build your own. When you go through the process of removing a persistent store and resetting the context, post your own notification-- @"MyAppCoreDataExploded"
or something. Observe this notification in any controller that uses managed objects. When you receive that notification, clean up any local references.
Upvotes: 0
Reputation: 8457
I have found that observing NSPersistentStoreCoordinatorStoresDidChangeNotification
works pretty well in my case.
It is being called twice – the first time, when the old persistent store is removed, the second time when the new store is added.
I am still testing wether this solution proofs better for my case than the one suggested by Nicholas.
Upvotes: 0
Reputation: 1724
Use NSNotificationCenter
to observe the NSManagedObjectContextObjectsDidChangeNotification
message, then examine the deletedObjects
method of your NSManagedObjectContext
. See the documentation for details: https://developer.apple.com/library/ios/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSManagedObjectContext_Class/NSManagedObjectContext.html#//apple_ref/occ/instm/NSManagedObjectContext/deletedObjects
Upvotes: 3