我无法将令人兴奋的核心数据堆栈更改为 NSPersistentCloudKitContainer,因为这只是 iOS 13 及更高版本的支持功能,但我希望为 iOS 13 及更高版本设置该功能,同时为早期版本设置 NSPersistentContainer。
我在使用 swift 和 iOS 方面有相当多的经验,但从来没有为版本控制和某些 var 做这样的事情。
这是我在使用 iOS 13 之前的正常操作:
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: "Shopping_App")
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
}()
这是我想在 iOS 13 或更高版本的任何设备上使用的,但仍将第一部分代码用于 iOS 12 及更早版本。
lazy var persistentContainer: NSPersistentCloudKitContainer = {
let container = NSPersistentCloudKitContainer(name: "Shopping_App")
container.loadPersistentStores(completionHandler: {
(storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
如果可能的话,我希望两个版本具有相同的变量,而不会重新声明错误,如果这甚至可能的话,如果那不可能,我想要一个不需要完全重写我的所有存储和检索的解决方案核心数据,数据。