Skip to content

Instantly share code, notes, and snippets.

@iosdevzone
Created November 10, 2023 00:09
Show Gist options
  • Save iosdevzone/88c881e78b3cabc17b7e22845969bd4a to your computer and use it in GitHub Desktop.
Save iosdevzone/88c881e78b3cabc17b7e22845969bd4a to your computer and use it in GitHub Desktop.
Update to ContentView.swift to synchronize Core Data context with Swift Data
// Modified version of ContentView.swift from Pol Piella's blog
// post "Using Core Data and Swift Data side by side".
//
// See: https://www.polpiella.dev/core-data-and-swift-data
//
// Crux is in the `onAppear`.
// ```
// .onAppear() {
// NotificationCenter.default.addObserver(forName: Notification.Name.NSManagedObjectContextDidSave,
// object: nil,
// queue: nil) { [self] (notification) in
// self.coreDataContext.mergeChanges(fromContextDidSave: notification)
// }
// ```
import SwiftUI
import SwiftData
struct ContentView: View {
@FetchRequest(sortDescriptors: [SortDescriptor(\.date, order: .reverse)])
var entries: FetchedResults<CoreDataDiaryEntry>
@Query
var swiftDataEntries: [DiaryEntry]
@Environment(\.modelContext) var swiftDataContext
@Environment(\.managedObjectContext) var coreDataContext
var body: some View {
VStack(spacing: 10) {
HStack {
VStack {
Text("Core data entity count")
Text("\(entries.count)")
}
VStack {
Text("Swift data entity count")
Text("\(swiftDataEntries.count)")
}
}
Spacer()
Button("New Swift Data entry", action: createSwiftDataEntry)
Button("New Core Data entry", action: createCoreDataEntry)
}
.buttonStyle(.borderedProminent)
.padding()
.onAppear() {
NotificationCenter.default.addObserver(forName: Notification.Name.NSManagedObjectContextDidSave,
object: nil,
queue: nil) { [self] (notification) in
self.coreDataContext.mergeChanges(fromContextDidSave: notification)
}
}
}
private func createSwiftDataEntry() {
let entry = DiaryEntry(title: "New entry!", body: "This is a Swift Data entry")
swiftDataContext.insert(entry)
}
private func createCoreDataEntry() {
let entry = CoreDataDiaryEntry(context: coreDataContext)
entry.date = .now
entry.title = "New entry!"
entry.body = "This is a CoreData entry"
try? coreDataContext.save()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment