xcode 在 Swift 3 中启用核心数据轻量级迁移

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39851950/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 09:23:24  来源:igfitidea点击:

Enabling core data lightweight migration in Swift 3

iosswiftxcodecore-dataswift3

提问by James

According to the articles I have read the correct way to enable core data light weight migrations is by passing options to addPersistentStoreWithType:

根据我阅读的文章,启用核心数据轻量级迁移的正确方法是将选项传递给addPersistentStoreWithType

let mOptions = [NSMigratePersistentStoresAutomaticallyOption: true,
NSInferMappingModelAutomaticallyOption: true]

try coordinator!.addPersistentStoreWithType(
NSSQLiteStoreType, configuration: nil, URL: url, options: mOptions)

But in my Xcode 8Swift 3project I can't find where addPersistentStoreWithTypeis called. This is the only core datacode that was generated when I created my project:

但是在我的Xcode 8Swift 3项目中我找不到addPersistentStoreWithType被调用的地方。这是core data我创建项目时生成的唯一代码:

 // MARK: - Core Data stack

lazy var persistentContainer: NSPersistentContainer = {
    /*
     The persistent container for the application. This implementation
     creates and returns a container, having loaded 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.
    */
    let container = NSPersistentContainer(name: "Habits")
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() 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.

            /*
             Typical reasons for an error here include:
             * The parent directory does not exist, cannot be created, or disallows writing.
             * The persistent store is not accessible, due to permissions or data protection when the device is locked.
             * The device is out of space.
             * The store could not be migrated to the current model version.
             Check the error message to determine what the actual problem was.
             */
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
    return container
}()

// MARK: - Core Data Saving support

func saveContext () {
    let context = persistentContainer.viewContext
    if context.hasChanges {
        do {
            try context.save()
        } catch {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() 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.
            let nserror = error as NSError
            fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
        }
    }
}

How do I enable lightweight migrations in Xcode 8 using Swift 3?

如何使用 Swift 3 在 Xcode 8 中启用轻量级迁移?

回答by Tom Harrington

You do it using NSPersistentStoreDescription, which is where all those options moved to in the Swift 3 updates. Do this before the call to loadPersistentStores:

你可以使用NSPersistentStoreDescription,这是所有这些选项在 Swift 3 更新中移到的地方。在调用之前执行此操作loadPersistentStores

let description = NSPersistentStoreDescription()

description.shouldInferMappingModelAutomatically = true
description.shouldMigrateStoreAutomatically = true

container.persistentStoreDescriptions = [description]

回答by Sweeper

You can just start a new project in Xcode 7, and copy and paste the generated core data code to the new new project!

您可以在 Xcode 7 中启动一个新项目,并将生成的核心数据代码复制并粘贴到新的新项目中!

I created a project in Xcode 7 and migrated it to Xcode 8, this is the generated code. (I have already added the two options for enabling lightweight stack migration)

我在 Xcode 7 中创建了一个项目并将其迁移到 Xcode 8,这是生成的代码。(我已经添加了启用轻量级堆栈迁移的两个选项)

// MARK: - Core Data stack

lazy var applicationDocumentsDirectory: URL = {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "com.MyApp" in the application's documents Application Support directory.
    let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    return urls[urls.count-1]
}()

lazy var managedObjectModel: NSManagedObjectModel = {
    // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
    let modelURL = Bundle.main.url(forResource: "MyApp", withExtension: "momd")!
    return NSManagedObjectModel(contentsOf: modelURL)!
}()

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
    // The persistent store coordinator for the application. This implementation creates and returns 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
    let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
    let url = self.applicationDocumentsDirectory.appendingPathComponent("SingleViewCoreData.sqlite")
    var failureReason = "There was an error creating or loading the application's saved data."
    do {
        try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: [NSMigratePersistentStoresAutomaticallyOption: true,NSInferMappingModelAutomaticallyOption: true])
    } catch {
        // Report any error we got.
        var dict = [String: AnyObject]()
        dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
        dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?

        dict[NSUnderlyingErrorKey] = error as NSError
        let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
        // 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 \(wrappedError), \(wrappedError.userInfo)")
        abort()
    }

    return coordinator
}()

lazy var managedObjectContext: NSManagedObjectContext = {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
    let coordinator = self.persistentStoreCoordinator
    var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
    managedObjectContext.persistentStoreCoordinator = coordinator
    return managedObjectContext
}()

// MARK: - Core Data Saving support

func saveContext () {
    if managedObjectContext.hasChanges {
        do {
            try managedObjectContext.save()
        } catch {
            // Replace this implementation 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.
            let nserror = error as NSError
            NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
            abort()
        }
    }
}

You can just copy the above and paste it in your App Delegate.

您可以复制以上内容并将其粘贴到您的 App Delegate 中。

One thing to note is that please edit this line so that it gets your data model's URL:

需要注意的一件事是,请编辑此行以获取您的数据模型的 URL:

let modelURL = Bundle.main.url(forResource: "MyApp", withExtension: "momd")!

回答by Michal

Note that both NSPersistentStore's shouldInferMappingModelAutomaticallyand shouldMigrateStoreAutomaticallyare trueby default.

请注意,NSPersistentStore'sshouldInferMappingModelAutomaticallyshouldMigrateStoreAutomatically都是true默认值。

Apple reference for:

苹果参考:

回答by Andrew Shon

In my case I make append to new description instead of replacement

在我的情况下,我将附加到新的描述而不是替换

let description = NSPersistentStoreDescription()
description.shouldInferMappingModelAutomatically = true
description.shouldMigrateStoreAutomatically = true
container.persistentStoreDescriptions.append(description)

回答by samwize

With the new NSPersistentContainerthere are many sensible defaults. You don't have to set the properties, which most of the answers give.

新的NSPersistentContainer有许多合理的默认值。您不必设置大多数答案所提供的属性。

Simply create the container and load.

只需创建容器并加载。

let container = NSPersistentContainer(name: dataModelName)
container.loadPersistentStores { storeDescription, error in
    // You may verify the default storeDescription has the right default for light migration
}