2

I'm trying to fetch some values out of a CoreData store, typed as an array of the generated CoreData Entity classes. Is this possible?

guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
let managedContext = appDelegate.persistentContainer.viewContext
let responseFetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Response")

do {
    var responses = try managedContext.fetch(responseFetchRequest) as! [Response]
    print(responses[0])
} catch {
    print("Failed!")
}

This print statement is only printing the following to console:

Printed entity object

Is it wrong to use these entity classes as such? I've used them before for creating data (see usage below), so surely you can use them as models too?

let responseEntity = NSEntityDescription.entity(forEntityName: "Response", in: managedContext)!
let response = Response(
    context: NSManagedObject(
        entity: responseEntity,
        insertInto: managedContext
    ).managedObjectContext!
)

Also, for context, this is what I mean by a CoreData entity:

CoreData entity

2
  • 1
    Your approach is fine. If you are concerned by the "relationship fault", please see this question and the various answers. Commented Mar 17, 2019 at 10:27
  • @pbasdf Ahh great, thanks for the tip. My main concern is that the data is coming back as nil though? Commented Mar 17, 2019 at 10:29

1 Answer 1

1

So I think your problem lies in the code where you create the objects:

let responseEntity = NSEntityDescription.entity(forEntityName: "Response", in: managedContext)!
let response = Response(
    context: NSManagedObject(
        entity: responseEntity,
        insertInto: managedContext
    ).managedObjectContext!
)

You are passing NSManagedObject(entity: responseEntity, insertInto: managedContext).managedObjectContext! into the context parameter of the initialiser. What that snippet does is to create a blank object, inserts it into managedContext, and then gets its managedObjectContext property. This happens before the Response object is initialised, so you are creating TWO objects with every call. Try changing to:

let response = Response(context: managedContext)

CoreData will infer the correct entity based on the class.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.