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'
?
A managed object context represents a single object space, or scratch pad, in a Core Data application. A managed object context is an instance of NSManagedObjectContext . Its primary responsibility is to manage a collection of managed objects.
NSPersistentContainer simplifies the creation and management of the Core Data stack by handling the creation of the managed object model ( NSManagedObjectModel ), persistent store coordinator ( NSPersistentStoreCoordinator ), and the managed object context ( NSManagedObjectContext ).
In some respects, an NSManagedObject acts like a dictionary—it's a generic container object that provides efficient storage for the properties defined by its associated NSEntityDescription instance.
As I mentioned earlier, the Core Data stack is the heart of Core Data. It's a collection of objects that make Core Data tick. The key objects of the stack are the managed object model, the persistent store coordinator, and one or more managed object contexts.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With