managedObjectContext in Swift 3

DaPhil picture DaPhil · Aug 29, 2016 · Viewed 15.6k times · Source

I want to work through this example code in which Swift and CoreData is used to create a table. However, using Swift 3 I fail to get it to work. Most importantly, I cannot properly replace the line

// set up the NSManagedObjectContext
  let appDelegate = NSApplication.sharedApplication().delegate as! AppDelegate
  managedContext = appDelegate.managedObjectContext

even though I found this related question (which however is iOS not OS X). How can I replace that piece of code which produces the error message Value of type 'AppDelegate' has no member 'managedContext'?

Answer

darksinge picture darksinge · Aug 31, 2016

Swift 3 in macOS

let appDelegate = NSApplication.shared().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext

The error you provided says 'AppDelegate' has no member 'managedContext' instead of 'AppDelegate' has no member 'managedObjectContext', which would lead me to assume you just need to fix your syntax.

Swift 3 in iOS 10

Core Data needs at least 3 things to work:

  1. A managed object model
  2. A persistent store coordinator
  3. And a managed object context

Put those three things together and you get the Core Data Stack.

When iOS 10 came out, a new object was introduced called the NSPersistentContainer which encapsulates the core data stack.

How to create the container object is answered here.

managedObjectContext is now a property called viewContext, accessed via:

let delegate = UIApplication.shared.delegate as! AppDelegate
let managedObjectContext = delegate.persistentContainer.viewContext

A helpful article is What's New in Core Data, but if that reading seems a little too heavy, this WWDC video does a great job of explaining this topic.