Reputation: 41
I am following a Udemy tutorial Link. This is my first time working with Core Data. This is what they have:
let context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
this is what I have:
let context = (UIApplication.shared.delegate as! AppDelegate).managedObjectContext
I get this error:
Value of type 'AppDelegate' has no member 'managedObjectContext'
Can anyone point me in the right direction to understand if it is a syntax problem or did I not create something.
Upvotes: 2
Views: 1690
Reputation: 3791
If you’ve checked/ticked “Use Core Data” when setting up your project, you should have a “pre-installed” Core Data “stack” in your AppDelegate
file, similar to that described in the Apple documentation titled “Core Data Stack”.
Your AppDelegate
should contain code similar to that detailed in the Apple documentation titled “Setting Up a Core Data Stack”, under the subheading “Initialize a Persistent Container”.
What it most likely does not include is a property for managedObjectContext
. The error explains this.
My guess is that you need to add a property for managedObjectContext
in your AppDelegate
file, similar to this...
LINE 1
var managedObjectContext: NSManagedObjectContext!
(Note that I’ve made this property an explicitly unwrapped optional !
.)
Then set this when you return your NSPersistentContainer
.
LINE 2
self.managedObjectContext = container.viewContext
These lines are placed as shown below...
class AppDelegate: UIResponder, UIApplicationDelegate {
...
var managedObjectContext: NSManagedObjectContext! //LINE 1
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "DataModel")
container.loadPersistentStores { description, error in
if let error = error {
fatalError("Unable to load persistent stores: \(error)")
}
}
self.managedObjectContext = container.viewContext //LINE 2
return container
}()
...
}
Upvotes: 2