【问题标题】:Swift 3 - "NSPersistentContainer is only available on ios 10 and newer"Swift 3 - “NSPersistentContainer 仅适用于 ios 10 及更高版本”
【发布时间】:2017-06-27 05:34:43
【问题描述】:

所以当我尝试将我的部署目标设置为 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 编程来说,我不确定具体要写什么。而且我似乎找不到任何答案来给出关于写什么的确切答案。有人可以帮忙吗?

【问题讨论】:

    标签: ios core-data swift3 deployment-target


    【解决方案1】:

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

    • 我使用了 pod 'INSPersistentContainer' 并在我的项目中安装了该 pod。
    • 通过此行在APpDelegate 中导入"import INSPersistentContainer"
    • 然后将NSPersistentContainer 替换为INSPersistentContainer

    仅此而已。

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

    【讨论】:

    • 那是第 3 方库对吧?我希望有一种方法可以通过没有 3rd 方库的代码来解决它。
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      NSPersistentContainer 仅适用于 iOS 10

      如果您仍然需要您的应用在以前的版本中运行,您可以使用在 iOS 10 中仍然可以使用的旧版 Core Data Stack

      另一种解决方案是在 swift 中使用 #available 属性来执行核心数据堆栈或 NSPersistentContainer。

      你可以关注https://stackoverflow.com/a/42392120/8023444这个答案同时支持ios 9和ios 10

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-16
        • 2018-07-04
        • 2020-08-25
        • 1970-01-01
        相关资源
        最近更新 更多