Search code examples
swiftxcodecore-datacode-generation

App crashes after setting CoreData Codegen to Category / Extension


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?

Solution

  • 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.