斯威夫特 3 - "NSPersistentContainer is only available on ios 10 and newer"



因此,当我尝试将部署目标设置为 iOS 9(实际上低于 10.0(时,我收到了标题中指出的错误。

问题存在于此处:

// 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: "Keebin_development_1")
    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
}()

查看不同的 SO 问题/答案,很明显我需要添加一些代码来区分 iOS 10 是否可用。 Swift 3 本身建议使用 @available(iOS 10.0, *) 。但这还不够。我希望这是因为我缺少"如果不可用,请使用这个",但是作为 Swift 和 iOS 编程的新手,我不确定具体写什么。而且我似乎找不到任何答案来给出关于写什么的确切答案。有人可以帮忙吗?

我遇到了同样的问题,我通过下面提到的方式解决了。我正在用 Swift 3.0 做项目。

  • 我使用了 pod 'INSPersistentContainer' 并将 pod 安装在我的项目中。
  • APpDelegate年通过该生产线进口"import INSPersistentContainer"
  • 然后将NSPersistentContainer替换为INSPersistentContainer

仅此而已。

现在我可以在较低版本的 iOS(

您真的不需要将iOS 10与早期版本区分开来。 NSPersistentContainer需要 iOS 10,但较旧的技术仍然有效并且仍然受支持。如果您需要支持 iOS <10,请不要使用 NSPersistentContainer 。加载托管对象模型和添加持久存储的步骤更多,但这样做意味着您可以为所有版本的 iOS 使用单个代码路径。

NSPersistentContainer仅在 iOS 10 中可用

如果您仍然需要您的应用程序在以前的版本中运行,您可以使用旧的核心数据堆栈,该堆栈在iOS 10中仍然有效

另一种解决方案是在 swift 中使用 #available 属性来执行 Core Data Stack 或 NSPersistentContainer。

您可以按照此答案 https://stackoverflow.com/a/42392120/8023444 支持ios 9和ios 10

相关内容

最新更新