When you enable default actor isolation—specifically to isolate code on the @MainActor—you may run into issues with autogenerated managed objects. By “autogenerated,” I’m referring to the code that Xcode generates for your Core Data entities.
Each entity in your Core Data model can be set to generate class definitions either automatically or manually. If you choose manual generation, you maintain full control, and default actor isolation poses little problem. However, if you rely on autogenerated classes, they don’t interact well with default actor isolation. In this lesson, we’ll explore how to address that issue.
Compiler errors in Swift 6 language mode
Before we dive into the solutions, I want to show you an example error you might run into:
After configuring Default Actor Isolation to @MainActor, errors like these are likely to show up. This is fine when you’re in control of the code, but tricky if not.
Manual codegeneration required
As of today, auto-generated code for entities does not respect the default actor isolation. Therefore, the only way out is to manually define your managed object classes. To be honest, this has always been my preference in Core Data projects. The auto-generated code always felt a bit hidden, and I love to be in control myself.
Solving Main actor-isolated issues
Once you’re in control of the code, you can also more easily solve incoming issues. Fortunately, these are relatively easy to solve. You simply have to opt-out of @MainActor isolation by using nonisolated:
nonisolated class Article: NSManagedObject { ... }
You need to do this for all your NSManagedObject instances.
Summary
Although this is a brief lesson, it addresses a common issue that arises when working with Core Data and the default actor isolation set to @MainActor. Hopefully, you were already using manual entity classes, which will make this solution easier to apply.