Integrating Core Data with SwiftUI
Over the years, you may have found different ways of using Core Data in your apps from an architectural point of view; for example, using Apple with the Xcode templates proposed to create containers in AppDelegate
so that you can use them when needed, other templates wrapped with Core Data inside manager classes, and so on. However, others prefer abstracting Core Data entirely so that it's easy to move to another solution, such as Realm, if needed.
SwiftUI's integration, however, points firmly in one direction: create the container when the app starts, inject it into our Environment
, and then use it to fetch data or make changes.
When building a new app with Xcode, you can check the Use Core Data checkbox so that Xcode creates a template that injects the Core Data stack in the most efficient way possible.
Even though this is the way we usually do this, in this recipe, we'll introduce Core Data manually in a SwiftUI project...