SwiftUIにCore Dataの使用 データ新規、変更と削除

管理用オブジェクト取得

まずはContentViewに@Environment(\.managedObjectContext) var contextを定義する。このcontextはCore Dataの管理用のオブジェクト。
context定義だけで使用できる原因は、プロジェクト作成時"Use Core Data"をチェックする時、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)

もしContentViewは他のCore Data操作があるSubViewを開く時、contextを渡すため、SubView().environment(\.managedObjectContext, self.context)のような書き方が必要。

データ新規追加

let taylor = Singer(context: context)
taylor.firstName = "Taylor"
taylor.lastName = "Swift"

let adele = Singer(context: context)
adele.firstName = "Adele"
adele.lastName = "Adkins"

try? context.save()

データの変更

singer.firstName = "AAA"
try? context.save()

データ削除

context.delete(singer)
try? context.save()

データ変更があるかどうかのチェック

if context.hasChanges {
    try? context.save()
}