How to create managedObjectContext using Swift 3 in Xcode 8?

Adelmaer picture Adelmaer · Jun 22, 2016 · Viewed 54.1k times · Source

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 Controller

let context = (UIApplication.shared().delegate as! AppDelegate).managedObjectContext

In Xcode 8 there is no code for managedObjectContext inside AppDelegate.swift file. Core Data stack code inside AppDelegate.swift presented only with: lazy var persistentContainer: NSPersistentContainer property and func saveContext () . There is no managedObjectContext property.

How to create managedObjectContext using Swift 3 in Xcode 8) or maybe there is no need to do it using Swift 3 ?

Answer

James Amo picture James Amo · Jun 26, 2016

In Swift3, you can access the managedObjectContext via the viewContext as

let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

This option is available if Core data was enabled when creating the project. However, for existing project that you want to include core data, go through the normal process of adding the core data and add the following code which will allow you to get the

lazy var persistentContainer: NSPersistentContainer = {

    let container = NSPersistentContainer(name: "you_model_file_name")
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error {

            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
    return container
}()

You will need to import the CoreData.

Note: For Swift3, the ManagedObject Subclass are generated automatically. See more from WWDC 2016