0

Context

My app uses CoreData and for the first version I was just using the Class Definition as the Codegen Method for all Entities. However, since I changed it to Category / Extension, the app crashes every time a View with a @FetchedResult Property Wrapper is loaded.

Crash Message: Thread 1: "executeFetchRequest:error: A fetch request must have an entity."


Code

// MyEntity.swift
public final class MyEntity: NSManagedObject {
    // ...
}

Questions

  • What causes the crash and how can I resolve it?
  • Is it necessary to define a new CoreData Model Version when only changing the Codegen Method?
  • Is the change of the Codegen Method supported by Lightweight Migration?
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
christophriepe
  • 1,157
  • 12
  • 47
  • When you changed the code gen style, did you create your own subclasses? If you’re using category/extension, you need to do that. – Tom Harrington Sep 23 '22 at 16:13
  • @TomHarrington Yes I did that, you can see one example of a custom created subclass in the Code Section above. Could the problem be, that I named the file just `MyEntity.swift`, without the `+CoreDataClass`? – christophriepe Sep 23 '22 at 16:14
  • The name of the file doesn't matter. What I think you must have before the class name is `@objc(MyEntity)` since I believe Core Data uses that. – Joakim Danielson Sep 23 '22 at 17:08
  • @JoakimDanielson Thank you for your reply. This solved the problem and using the CD Entities works fine now. What about the 2. and 3. question regarding the need of a new Model Version? Feel free to post your reply as an answer, so that I can accept it and close the question. – christophriepe Sep 23 '22 at 17:27
  • The answer to 2 is No since nothing has changed to the model itself. This means 3 is not relevant. – Joakim Danielson Sep 23 '22 at 17:29
  • @JoakimDanielson Thanks a lot for your answers. Feel free to post it as one. – christophriepe Sep 24 '22 at 06:13

1 Answers1

1

When creating your own subclass for a Core Data entity you must add the attribute @objc() to the declaration so that Core Data can find and use your subclass

@objc(MyEntity)
public final class MyEntity: NSManagedObject {
    // ...
}

As for changing the type of codegen it will not affect the Core Data model in anyway so there is nothing that needs to be migrated.

Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52