NEW: Learn SwiftUI with my free YouTube video series! >>

< Introduction to using Core Data with SwiftUI   How to access a Core Data managed object context from a SwiftUI view >

How to configure Core Data to work with SwiftUI

If you create a new project and check both SwiftUI and Core Data, Xcode does a pretty good job of getting you towards a working configuration. Specifically, it:

  1. Creates an empty YourProjectName.xcdatamodeld model file.
  2. Adds a persistentContainer lazy property to the app delegate, that loads the model file into a container.
  3. Adds a saveContext() method to the app delegate that will check for changes and save if needed.
  4. Calls that saveContext() method from the scene delegate’s sceneDidEnterBackground() method, ensuring that Core Data updates are flushed when the scene moves to the background.

One part of the puzzle it doesn’t include is injecting the managed object context into the SwiftUI environment, but that requires only one small change to SceneDelegate.swift – look for this line inside the willConnectTo method:

window.rootViewController = UIHostingController(rootView: ContentView()

Now replace it with this:

guard let container = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer else {
    fatalError("Unable to read managed object context.")
}

window.rootViewController = UIHostingController(rootView: ContentView().environment(\.managedObjectContext, container.viewContext))

That reads the NSPersistentContainer that Xcode’s template created in the app delegate, and passes it into the environment using the \.managedObjectContext key.

Now, because Core Data requires some sort of configuration to get meaningful results all the chapters in this Core Data section use a shared configuration that I won’t keep on repeating.

First, make sure you create a new Single View App that enables both SwiftUI and Core Data support.

Second, apply the changes listed directly above in “Xcode’s default template” to inject the managed object context into the environment.

Third, open your xcdatamodeld file and create an entity called ProgrammingLanguage that has two string attributes: “name” and “creator”. Obviously you don’t need to have exactly this entity and attribute collection, so just mentally replace my examples with your own Core Data setup as you go.

Finally, in the data model inspector please change Codegen to be “Class Definition” – this will generate a Language class for us that SwiftUI can work with.

Important: those instructions matter!

To avoid confusion, I want to repeat that the instructions above are important for setting up a useful Core Data environment for SwiftUI. All subsequent Core Data chapters assume you have followed the instructions above.

SPONSOR Meet the new Instabug – more than just bug reporting! We help you build better apps and minimize your debugging time. With each bug report, we automatically capture details like network requests, repro steps, and session details. Get real-time crash reports with stack trace details and session data to help you catch and fix issues easily. And with our customizable in-app surveys, you’ll gather insightful user feedback and much more. Instabug is the fastest and easiest way to release with confidence. Start your free trial now! Start your free trial now!

< Introduction to using Core Data with SwiftUI   How to access a Core Data managed object context from a SwiftUI view >
MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Click here to visit the Hacking with Swift store >>