【问题标题】:Is Core Data Model Migration Required when changing Attribute Type from Int16 to Int64将属性类型从 Int16 更改为 Int64 时是否需要核心数据模型迁移
【发布时间】:2016-03-16 08:59:21
【问题描述】:

我已将数据模型的属性类型从 Int16 更改为 Int64。它是否需要迁移,否则它将自动作为其相同的数据类型 Int 工作。请指导。

【问题讨论】:

    标签: ios xcode swift core-data core-data-migration


    【解决方案1】:

    是的,您可以更改属性类型并在 core-data 中迁移您的数据存储,但是在创建/配置您的 NSPersistentStoreCoordinator 时,您需要设置一些我在下面提到的选项。这是我们在这里所做的core-data 中的LightWeight Migration 调用。

    使用以下代码更新您的 persistentStoreCoordinator 初始化方法。

    - (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
        // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it.
        if (_persistentStoreCoordinator != nil) {
            return _persistentStoreCoordinator;
        }
    
        // Create the coordinator and store
        _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    
        // *** add support for light weight migration ***
        NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                                 [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
                                 [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption,
                                 nil];
    
        NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"StoreName.sqlite"];
        NSError *error = nil;
    // *** Add support for lightweight migration by passing options value ***
        if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]) {
    
            // Replace this with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        }
    
        return _persistentStoreCoordinator;
    }
    

    您可以在以下站点阅读有关核心数据迁移的更多信息。

    1. Apple official documentation

    2. Other site

    【讨论】:

    • 感谢您的回答。但我对此并不陌生。你能告诉我把这段代码放在哪里吗?
    • 我已经更新了我的答案,你需要替换你的 persistenceStoreCoordinator 初始化方法。
    • 刚刚意识到该项目正在使用神奇的记录来存储核心数据。有没有更简单的方法可以用这个插件做到这一点?我还需要创建一个包含更改的新数据模型吗?
    • 在MagicalRecord中使用[MagicalRecord setupCoreDataStackWithAutoMigratingSqliteStoreNamed:####];这个方法进行轻量级迁移。
    猜你喜欢
    • 1970-01-01
    • 2020-09-19
    • 1970-01-01
    • 2013-11-16
    • 1970-01-01
    • 2018-08-15
    • 1970-01-01
    • 1970-01-01
    • 2016-09-07
    相关资源
    最近更新 更多