NSPersistentContainer仅在10.0或更新版本中可用:错误

这是因为我的部署目标小于10。

如何解决部署目标低至10.0?

在此处输入图像描述

解决方案之一是使用https://github.com/inspace-io/INSPersistentContainer

并添加

typealias NSPersistentContainer = INSPersistentContainer typealias NSPersistentStoreDescription = INSPersistentStoreDescription 

到你想要使用的文件

不可用表示不可用。

有两种选择:

  • 仅使用旧的 NSPersistentStoreCoordinator / NSManagedObjectModel模式。
  • if #available(iOS 10, *)请使用这两种模式并使用可用性检查编写代码

在iOS 10之前

您可以直接从AppDelegate.h访问NSManagedObjectContext

 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 if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext 

( 原始代码 )

来自iOS 10及更新版本

这已更改, NSManagedObjectContext已移入PersistentContainer进入属性viewContext

 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: "") ... ... 

( 原始代码 )

因此,您需要区分运行应用程序的版本,然后调用正确的函数。 AppDelegate中的ManagedObjectContext或[PersistentContainer viewContext]中的ManagedObjectContext。

顺便说一句:在iOS 10之前的版本教程要小心。

像这样使用@available标签: @available(iOS 10.0, *) lazy var persistentContainer: NSPersistentContainer = ...