How to create managedObjectContext using Swift 3 in Xcode 8?

前端 未结 5 2124
无人共我
无人共我 2020-11-27 03:13

Facing issue \"Value of type \'AppDelegate\' has no member \'managedObjectContext\' In new Xcode 8 (using Swift 3, iOS 10) when trying to create new context in View Controll

5条回答
  •  爱一瞬间的悲伤
    2020-11-27 03:38

    The solution by James Amo gets you most of the way there for iOS 10.0, but doesn't address iOS 9.0 and below, which can't access that method and needs to manually build the NSManagedObjectModel. Here is the solution that worked for me:

        var context: NSManagedObjectContext?
    
        if #available(iOS 10.0, *) {
            context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        } else {
            // iOS 9.0 and below - however you were previously handling it
            guard let modelURL = Bundle.main.url(forResource: "Model", withExtension:"momd") else {
                fatalError("Error loading model from bundle")
            }
            guard let mom = NSManagedObjectModel(contentsOf: modelURL) else {
                fatalError("Error initializing mom from: \(modelURL)")
            }
            let psc = NSPersistentStoreCoordinator(managedObjectModel: mom)
            context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
            let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
            let docURL = urls[urls.endIndex-1]
            let storeURL = docURL.appendingPathComponent("Model.sqlite")
            do {
                try psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: nil)
            } catch {
                fatalError("Error migrating store: \(error)")
            }
    
        }
    

    It's clear that the change to 10.0 makes CoreData significantly simpler, but it's unfortunate that it's so painful for existing developers to make the jump...

    To implement the above, just make sure to throw the persistentContainer into your AppDelegate.swift, defined in James Amo's answer.

提交回复
热议问题