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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…