Chapter 13: Handling Core Data in SwiftUI
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's view.
Also, NSManagedObjectContext
is injected into the environment of the View's hierarchy so that SwiftUI's View 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.