これまでもCoreDataを使ってきていましたが、iOS13になって、SwiftUIともつながりやすくなったとも聞いたので、CoreDataのセットアップコードに変化があったのかを見てみました。
チェックした環境
- XCode11.4
- iOS13, macOS Catalina
CoreData向けに追加されるコード
AppDelegate内に、以下のコードが追加されます。
lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "Bookworm") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } }
上記のコードは、SwiftUIになっても特に変更はありません。従来のCoreDataサポートを設定したプロジェクトで生成されていたコードと同じです。
SceneDelegate.swiftにもコードが追加されています。
// Get the managed object context from the shared persistent container. let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext // Create the SwiftUI view and set the context as the value for the managedObjectContext environment keyPath. // Add `@Environment(\.managedObjectContext)` in the views that will need the context. let contentView = ContentView().environment(\.managedObjectContext, context)
前半の”let context = …”が、新規に追加された行で、後半の”let contentView = …”は、既存の行に”.environment…”以降が既存の行に追加されたものとなっています。
コードやコメントの通りですが、AppDelegateで保持されているpersistentContainerの中のManagedObjectContextを、environmentObjectとして設定しています。
MacOS向けのDocument-basedだとどうなる?
Document.swift内に以下のコードが追加されました。
override func makeWindowControllers() { // Create the SwiftUI view and set the context as the value for the managedObjectContext environment keyPath. // Add `@Environment(\.managedObjectContext)` in the views that will need the context. let contentView = ContentView().environment(\.managedObjectContext, self.managedObjectContext!) // Create the window and set the content view. ... }
違いは、let contentView =ContentView().environment …の箇所ですね。
ここで、ContentViewにEnvironmentObjectを明示的に設定してますね。
iOSのアプリであれば、1つのドキュメントなので、Framework内で遮蔽できるけれど、MacOSでDocument-Basedの場合には、
異なるドキュメントを対象にしたビューが複数開かれるかもしれないために、ここでEnvironmentObjectを設定してるんでしょうね。
# コメントでもきちんと説明してくれてますね。親切。
違いは?
Document-basedアプリの時に、EnvironmentObjectを設定するコードが付加されていましたが、それ以外については、
以前に生成されていたコードと同じでした。
ということは、Environment等のオブジェクトで紐づけられていることで、連携しやすくなっているので、
アプリ側でのセットアップに変更はほぼなくて、Framework側の努力(?)で接続性が良くなっているという理解で良いようです。
Sponsor Link