NSPersistentContainer is only available in 10.0 or newer : error

后端 未结 4 628
猫巷女王i
猫巷女王i 2021-01-05 21:09

It\'s because My deployment target is less than 10.

how to resolve for deployment target lower to 10.0 ?

4条回答
  •  梦谈多话
    2021-01-05 21:50

    Before iOS 10

    you could access the NSManagedObjectContext directly from AppDelegate.h

    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
    

    (Original code)

    from iOS 10 and newer

    this changed and the NSManagedObjectContext has been moved into the PersistentContainer into the attribute 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: "")
    ...
    ...
    

    (original code)

    So, you need to distinguish which version you're app is running on and then call the correct function. ManagedObjectContext inside AppDelegate or The ManagedObjectContext inside [PersistentContainer viewContext].

    btw: Be careful with tutorials for versions before iOS 10.

提交回复
热议问题