NSPersistentContainer is only available in 10.0 or newer : error

后端 未结 4 612
猫巷女王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:31

    Not available means not available.

    There are two options:

    • Use only the old NSPersistentStoreCoordinator / NSManagedObjectModel pattern.
    • Use both patterns and write the code with availability checking if #available(iOS 10, *)
    0 讨论(0)
  • 2021-01-05 21:31

    Use the @available tag like this: @available(iOS 10.0, *) lazy var persistentContainer: NSPersistentContainer = ...

    0 讨论(0)
  • 2021-01-05 21:45

    One of solutions is to use https://github.com/inspace-io/INSPersistentContainer

    and add

    typealias NSPersistentContainer         = INSPersistentContainer
    typealias NSPersistentStoreDescription  = INSPersistentStoreDescription
    

    to your file where you want to use

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题