Search code examples
ioscore-dataautomatic-ref-countingnsmanagedobjectcontext

CoreData: Replace .sqlite causes crash


When I update my app, I'm doing some stuff with my CoreData model on startup and afterwards I replace the .sqlite file the persistent store uses with:

NSArray *stores = [__persistentStoreCoordinator persistentStores];

for(NSPersistentStore *store in stores) {
    [__persistentStoreCoordinator removePersistentStore:store error:nil];
    [[NSFileManager defaultManager] removeItemAtPath:store.URL.path error:nil];
}
__persistentStoreCoordinator = nil;
[self persistentStoreCoordinator];

__managedObjectContext = nil;
[self managedObjectContext];

Everything works fine, just the way it is suposed to. But when I close the app via the homebutton, it crashes:

[NSPersistentStoreCoordinator retain]: message sent to deallocated instance

I'm using ARC ... actually you could say it doesn't matter, because it crashes when being closed, so you don't notice the crash. But, of course, that's not an option and there has to be a right way to do that!?

Any ideas? Why is there a retain sent to the NSPersistenStoreCoordinator? It has something to do with __persistentStoreCoordinator = nil; but I need to nil it, otherwise it doesn't use the new .sqlite.

Cheers!


Solution

  • Well finaly I found a better (and working) way to replace the .sqlite & storeCoordinator's store, without the need to nil the persistentStoreCoordinator:

    NSArray *stores = [__persistentStoreCoordinator persistentStores];
    
    for(NSPersistentStore *store in stores) {
        [__persistentStoreCoordinator removePersistentStore:store error:nil];
        [[NSFileManager defaultManager] removeItemAtPath:store.URL.path error:nil];
    }
    
    NSString *storePath = [[self applicationDocumentsDirectoryString] stringByAppendingPathComponent:@"PictureApp.sqlite"];
    
    NSURL *storeUrl = [NSURL fileURLWithPath:[[self applicationDocumentsDirectoryString] stringByAppendingPathComponent:@"PictureApp.sqlite"]];
    
    NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"PictureApp" ofType:@"sqlite"];
    if (defaultStorePath) {
        [[NSFileManager defaultManager] copyItemAtPath:defaultStorePath toPath:storePath error:NULL];
    }
    
    NSError *error = nil;
    [__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:options error:&error];