1

I have made significant changes to my database, so much so that now it is better to remove the whole database and then load all the data again. I found out how to remove all objects from the database here: Delete/Reset all entries in Core Data?

But how do I detect that there is a model of my database and then delete all the data related to the old one? I am assuming I can do it here somewhere?

- (NSPersistentStoreCoordinator *)privatePersistentStoreCoordinator
{

    if (_privatePersistentStoreCoordinator != nil) {
        return _privatePersistentStoreCoordinator;
    }

    NSString *urlString= [NSString stringWithFormat:@"db.sqlite"];

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:urlString];

    NSError *error = nil;
    _privatePersistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![_privatePersistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL nil error:&error]) {
        //CODE TO MAKE NEW DATABASE??

        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    return _privatePersistentStoreCoordinator;
}
Community
  • 1
  • 1
Nilsymbol
  • 515
  • 1
  • 9
  • 25

1 Answers1

0

If you're doing this to solve the "data model is not the same` crash, you can delete the file and create a new one in your persistent store coordinator like so:

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
    // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
    // Create the coordinator and store
    var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
    let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("Data.sqlite")
    var error: NSError? = nil
    var failureReason = "There was an error creating or loading the application's saved data."
    if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
        coordinator = nil
        // Report any error we got.
        let dict = NSMutableDictionary()
        dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
        dict[NSLocalizedFailureReasonErrorKey] = failureReason
        dict[NSUnderlyingErrorKey] = error
        error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)

        println("Unresolved error \(error), \(error!.userInfo)")

        if NSFileManager.defaultManager().fileExistsAtPath(url.path!) {
            if NSFileManager.defaultManager().removeItemAtPath(url.path!, error: nil) {

                var newCoordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)

                if newCoordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) != nil {
                    return newCoordinator
                }
            }
        }
    }

    return coordinator
}()

I don't do much in objective-C anymore so yeah the answer is in Swift, but it shouldn't be difficult to convert at all. The only lines you need to add are:

if NSFileManager.defaultManager().fileExistsAtPath(url.path!) {
    if NSFileManager.defaultManager().removeItemAtPath(url.path!, error: nil) {
_privatePersistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];

        if newCoordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) != nil {
            return newCoordinator
        }
    }
}

It might look something like this:

if ([[NSFileManager defaultManager] fileExistsAtPath(url.path!)]) {
    if ([[NSFileManager defaultManager] removeItemAtPath(url.path!, error: nil)]) {
        var newCoordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)

        if (![_privatePersistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL nil error:&error]) {
            return _privatePersistentStoreCoordinator;
        }
    }
}
Ian
  • 12,538
  • 5
  • 43
  • 62
  • I really don't get your answer at all. I don't know any swift at all so could you explain the logic behind your code and maybe then I can figure it out? Thank you – Nilsymbol Feb 13 '15 at 19:05
  • Basically where the `abort` is called in your code, you replace it with code that checks to see if the persistent store exists, if it does, you remove it and create a new one. – Ian Feb 13 '15 at 19:12
  • updated answer. I freehanded it so you might have to change some stuff – Ian Feb 13 '15 at 19:21