How to create managedObjectContext using Swift 3 in Xcode 8?

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

Leave a Comment