I'm a newbie in working with SwiftData and I hope for your help in solving the below issue :")
It's about adding new objects into a Model, it takes about 30 seconds to save the data after executing modelContext.insert().
Just run the source code below, tap on "Add" button to add some samples, and then tap on "Delete" button right away. Delete action doesn't work immediately, but it's about 30 seconds after tapping on the "Add" button, it will work - the sample data are deleted properly.
I tested and found this issue happens on both Preview and Simulator of:
- Xcode 15.0 (15A240d) and iOS 17.0
- Xcode 15.1 beta (15C5042i) with iOS 17.2
Full source code on GitHub
Bike.swift
import Foundation
import SwiftData
@Model class Bike {
var name: String
init(name: String) {
self.name = name
}
}
TestApp.swift
import SwiftUI
import SwiftData
@main
struct TestApp: App {
var body: some Scene {
WindowGroup {
BikeListView()
}
.modelContainer(for: Bike.self)
}
}
BikeListView.swift
import SwiftUI
import SwiftData
struct BikeListView: View {
@Environment(\.modelContext) var modelContext
@Query var bikes: [Bike]
var body: some View {
VStack {
HStack(spacing: 30) {
Button {
addSamples()
} label: {
Text("Add")
}
Button {
deleteSamples()
} label: {
Text("Delete")
}
}
List {
ForEach(bikes) { eachBike in
Text(eachBike.name)
}
}
}
}
func addSamples() {
let bikeOne = Bike(name: "One")
let bikeTwo = Bike(name: "Two")
modelContext.insert(bikeOne)
modelContext.insert(bikeTwo)
}
func deleteSamples() {
try? modelContext.delete(model: Bike.self)
}
}
#Preview {
do {
let modelConfig = ModelConfiguration(isStoredInMemoryOnly: true)
let modelContainer = try ModelContainer(for: Bike.self, configurations: modelConfig)
return BikeListView() .modelContainer(modelContainer)
} catch {
fatalError("Content View's Preview")
}
}
Thanks for reading and I'm looking forward to your help.