My core data fetch is not recognizing context

176 Views Asked by At

In my swift code below I am trying to fetch all of my names in core data to print. I am getting a compile error on context saying it can't be found in scope. I have attached a photo as well so you can see what is in my core data.

@objc func pressRight(){
 
    var locations  = [Place]() // Where Locations = your NSManaged Class

    var fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "name")
    locations = context.executeFetchRequest(fetchRequest, error: nil) as [Place]

    // Then you can use your properties.

    for location in locations {

      print(location.name)

    }

   
    
}

enter image description here

1

There are 1 best solutions below

0
Tom Harrington On

This isn't a Core Data problem, it's a Swift problem. All variables and properties in Swift have to be declared before you can use them. For example you can't just write

i = 5

Unless somewhere you already have something like

var i: Int

In your code you're using something called context that was never declared. Swift doesn't know what it is, which is what it's telling you.

Since you're using Core Data it looks like you want context to be an instance of NSManagedObjectContext. If your app already has an NSPersistentContainer somewhere, you can get a context from it, using either viewContext or newBackgroundContext (which one depends on exactly how you're using it; here it's probably viewContext).

If you don't already have an NSPersistentContainer somewhere in your app, you may want to read up a little on how to use Core Data. You can't just declare the context; it needs to be configured correctly with the container before use.