2

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Mack.Live
  • 41
  • 4
  • Are you sure you selected Core Data when you created the project? – koen Oct 04 '19 at 16:26
  • 1
    Is the Core Data stack present in AppDelegate? When creating a new project you have to check `Use Core Data` to get the Core Data stack. – vadian Oct 04 '19 at 16:33
  • Possible duplicate of [How to create managedObjectContext using Swift 3 in Xcode 8?](https://stackoverflow.com/questions/37956720/how-to-create-managedobjectcontext-using-swift-3-in-xcode-8) – timbre timbre Oct 04 '19 at 16:55
  • Yes, I have the 2 files Item+CoreDataClass.swift & Item+CoreDataProperties.swift. – Mack.Live Oct 04 '19 at 18:30

1 Answers1

2

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
    }()

    ... 
}
andrewbuilder
  • 3,629
  • 2
  • 24
  • 46