核心数据,如何在版本控制时删除整个数据库

core data, how to remove entire database upon versioning

我对我的数据库进行了重大更改,以至于现在最好删除整个数据库,然后重新加载所有数据。我在这里找到了如何从数据库中删除所有对象:Delete/Reset all entries in Core Data?

但是如何检测到我的数据库有模型,然后删除所有与旧模型相关的数据?我假设我可以在这里的某个地方做?

- (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;
}

如果您这样做是为了解决“数据模型不一样”崩溃,您可以删除该文件并在持久存储协调器中创建一个新文件,如下所示:

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
}()

我不再在 objective-C 中做太多,所以是的,答案在 Swift 中,但转换起来应该不难。您需要添加的唯一行是:

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
        }
    }
}

它可能看起来像这样:

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;
        }
    }
}