核心数据迁移:如何删除核心数据堆栈?

ma1*_*w28 12 iphone core-data objective-c core-data-migration ios

我的计划是删除旧的Core Data堆栈(NSManagedObjectModel .momd文件和NSPersistentStore .sqlite文件),因为:

  • 我没有Core Data迁移的经验.
  • 新的.xcdatamodel架构与旧架构完全不同.
  • 我可以安全地删除用户的旧数据,因为它全部存储在我们的服务器上,新应用程序无论如何都会从我们的服务器下载最新的数据.

在这种情况下,是否完全删除了迁移的最佳方式?

Cos*_*que 14

如果您的应用程序需要互联网访问,这是完全有效的事情.否则,用户可能会留下一个空数据集(当您发现它与当前模型不兼容时删除旧数据库,但如果不访问服务器则无法重新填充它).

从技术上讲,这是一件微不足道的事情.当你设置NSPersistentStoreCoordinator:

NSURL *storeURL = ...;
NSManagedObjectModel *managedObjectModel = ...;
NSError *error = nil;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: managedObjectModel];

// Check if we already have a persistent store
if ( [[NSFileManager defaultManager] fileExistsAtPath: [storeURL path]] ) {
    NSDictionary *existingPersistentStoreMetadata = [NSPersistentStoreCoordinator metadataForPersistentStoreOfType: NSSQLiteStoreType URL: storeURL error: &error];
    if ( !existingPersistentStoreMetadata ) {
        // Something *really* bad has happened to the persistent store
        [NSException raise: NSInternalInconsistencyException format: @"Failed to read metadata for persistent store %@: %@", storeURL, error];
    }

    if ( ![managedObjectModel isConfiguration: nil compatibleWithStoreMetadata: existingPersistentStoreMetadata] ) {
        if ( ![[NSFileManager defaultManager] removeItemAtURL: storeURL error: &error] )
            NSLog(@"*** Could not delete persistent store, %@", error);
    } // else the existing persistent store is compatible with the current model - nice!
} // else no database file yet

[_persistentStoreCoordinator addPersistentStoreWithType: NSSQLiteStoreType 
                                          configuration: nil 
                                                    URL: storeURL 
                                                options: nil 
                                                  error: &error];
Run Code Online (Sandbox Code Playgroud)