I'm a newbie in working with SwiftData and I hope for your help in solving the below issue :")
It's about deleting the objects into a Model by ModelContext.delete(). It's only possible to delete the data after it has been inserted for about 30 seconds.
Just run the source code below, tap on "Add" button to add some samples, and then tap on "Delete" button right away. At this time, Delete action doesn't work. You have to wait about 30 seconds, then tap on "Delete" button, it will work - the sample data are deleted properly.
I tested this issue on Xcode 15.1 beta (15C5042i) and found that:
- This issue always happens on Preview w/ iOS 17 or iOS 17.2.
- This issue doesn't happen on Simulator w/ iOS 17 BUT it happens on Simulator w/ iOS 17.2
Is this an issue of 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: false)
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.