Skip to content

Instantly share code, notes, and snippets.

@quellish
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quellish/75e676cf983f10625a7d to your computer and use it in GitHub Desktop.
Save quellish/75e676cf983f10625a7d to your computer and use it in GitHub Desktop.
23283661
1. Add two methods to handle the notification. You want to create and add a new store when the old one has been removed.
- (void) didChangePersistentStores:(id)notification {
NSArray *addedStores = nil;
NSArray *removedStores = nil;
NSArray *uuidChangedStores = nil;
addedStores = [[notification userInfo] valueForKey:NSAddedPersistentStoresKey];
removedStores = [[notification userInfo] valueForKey:NSRemovedPersistentStoresKey];
uuidChangedStores = [[notification userInfo] valueForKey:NSUUIDChangedPersistentStoresKey];
for (NSPersistentStore *store in removedStores){
[self didRemovePersistentStore:store];
}
}
- (void) didRemovePersistentStore:(NSPersistentStore *)persistentStore {
NSError *error = nil;
if (![[self persistentStoreCoordinator] addPersistentStoreWithType:NSInMemoryStoreType configuration:nil URL:[NSURL URLWithString:@"memory://0"] options:nil error:&error]) {
}
}
2. Listen for the notification.
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didChangePersistentStores:) name:NSPersistentStoreCoordinatorStoresDidChangeNotification object:_persistentStoreCoordinator];
3. In your "resetStack" method, remove the store and set the managed object context to nil as noted in the question's comments:
NSError *persistentStoreError = nil;
_managedObjectContext = nil;
[[self persistentStoreCoordinator] removePersistentStore:[[self persistentStoreCoordinator] persistentStoreForURL:[NSURL URLWithString:@"memory://0"] ] error:&persistentStoreError];
Make sure you recreate any fetched results controllers that may be using this managed object context. You can do this any number of ways - have them listen for the same notification, for example, or using KVO to react to changes to the managed object context your view controller was passed.
Note that when using the "lazy instantiation" pattern on these accessors for the managed object context, coordinator, etc. it's likely you will run into issues later. For example, here we are having to directly access the ivar _managedObjectContext. This is not good.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment