Persistence in SwiftUI with Core Data and SwiftData
Core Data is one of the most essential Apple frameworks in the iOS and macOS ecosystem. Core Data provides persistence, which means it can save data outside the app’s memory, and the data you save can be retrieved after you restart your app. Given its importance, it’s not a surprise that Apple has implemented some extensions for Core Data to make it work nicely with SwiftUI. In Core Data language, a stored object is an instance of NSManagedObject
, which conforms to the ObservableObject
protocol so that it can be observed directly by a SwiftUI view. Also, NSManagedObjectContext
is injected into the environment of the view hierarchy so that SwiftUI views can access it to read and change its managed objects. A very common feature of Core Data is that you can fetch objects from its repository. For this purpose, SwiftUI provides the @FetchRequest
property wrapper, which can be used in a view to load data. When you create...