Integrating Core Data with SwiftUI
If you’re familiar with iOS development, over the years, you may have found different ways of using Core Data in your apps from an architectural point of view. For example, Apple, before iOS 14, provided Xcode templates that created the Core Data containers in the AppDelegate
. Other developers prefer to wrap Core Data inside custom classes, abstracting Core Data entirely, while encapsulating the whole Core Data Stack and its managed objects in a module. By abstracting the persistence code, it will be easy to move to another persistence solution, such as Realm (
https://realm.io)
, if needed.
SwiftUI’s integration, however, points firmly in one direction: create the container when the app starts, inject it into the 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...