如何升级到新的CoreDataStack-NSPersistentContainer

时间:2019-09-09 07:56:05

标签: swift xcode core-data

我们有一个使用NSPersistentStore的旧传统Core Data Stack,我想升级到新的Core Data Stack并使用NSPersistentContainer。但似乎我缺少一些配置,并且无法正常工作。

我尝试使用与旧NSPersistentStore使用相同的URL。 另外,我在Xcode 10和Xcode 11上遇到了不同的错误。

旧版代码:

_oldStoreUrl = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:APP_GROUP_IDENTIFIER];
    _oldStoreUrl = [_oldStoreUrl URLByAppendingPathComponent:@"MyModel.sqlite"];

    NSError *error = nil;
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSDictionary *options = @{
                              NSPersistentStoreFileProtectionKey: NSFileProtectionCompleteUntilFirstUserAuthentication,
                              NSMigratePersistentStoresAutomaticallyOption: [NSNumber numberWithBool:YES],
                              NSInferMappingModelAutomaticallyOption: [NSNumber numberWithBool:YES]
                              };
    NSPersistentStore *store = [_persistentStoreCoordinator addPersistentStoreWithType:[self persistentStoreType]
                                                                         configuration:nil
                                                                                   URL:_oldStoreUrl
                                                                               options:options
                                                                                 error:&error];

新代码:

guard let storeDirectory = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: APP_GROUP_IDENTIFIER) else {
            fatalError("Unable to load Application Directory")
        }

        let persistentName = "MyModel"
        let container = NSPersistentContainer(name: persistentName)

        let url = storeDirectory.appendingPathComponent("\(persistentName).sqlite")
        let description = NSPersistentStoreDescription(url: url)
        description.shouldInferMappingModelAutomatically = true
        description.shouldMigrateStoreAutomatically = true
        container.persistentStoreDescriptions = [description]


        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })

即时通讯收到的错误: Xcode 11:

[error] CoreData: One or more models in this application are using transformable properties with transformer names that are either unset, or set to NSKeyedUnarchiveFromDataTransformerName. Please switch to using "NSSecureUnarchiveFromData" or a subclass of NSSecureUnarchiveFromDataTransformer instead. At some point, Core Data will default to using "NSSecureUnarchiveFromData" when nil is specified, and transformable properties containing classes that do not support NSSecureCoding will become unreadable.

0 个答案:

没有答案