I constructed a minimization program to simplify issues:
Mannequin:
import RealmSwift
class House: Object, Identifiable {
@Endured(primaryKey: true) var id: ObjectId
@Endured var identify: String = ""
comfort init(identify: String) {
self.init()
self.identify = identify
}
}
ViewModel:
import Basis
import RealmSwift
class SpaceStore: ObservableObject {
@Revealed var areas: Outcomes<House>?
non-public static let realm = attempt! Realm()
non-public var realmToken: NotificationToken?
init() {
let outcomes = SpaceStore.realm.objects(House.self)
realmToken = outcomes.observe { _ in
self.areas = outcomes
}
}
func add(by identify: String) {
let area = House(identify: identify)
attempt! SpaceStore.realm.write {
SpaceStore.realm.add(area)
}
}
func delete(_ area: House) {
attempt! SpaceStore.realm.write {
SpaceStore.realm.delete(area)
}
}
}
ContentView:
import SwiftUI
struct ContentView: View {
@EnvironmentObject var retailer: SpaceStore
var physique: some View {
Button("Add") {
retailer.add(by: "qwerty")
}
Divider()
if let areas = retailer.areas {
ForEach(areas) { area in
HStack {
Textual content(area.identify)
Button("Delete") {
retailer.delete(area)
}
}
}
Divider()
if let spaceItem = areas.first {
ItemView(area: spaceItem)
}
Divider()
ForEach(areas) { area in
// RowView(area: area)
}
}
}
}
#Preview {
ContentView()
.environmentObject(SpaceStore())
}
ItemView:
import SwiftUI
struct ItemView: View {
let area: House
@EnvironmentObject var retailer: SpaceStore
var physique: some View {
HStack {
Textual content(area.identify)
Button("Delete") {
retailer.delete(area)
}
}
}
}
#Preview {
ItemView(area: House(identify: "e"))
.environmentObject(SpaceStore())
}
The doorway:
import SwiftUI
@predominant
struct ForTestApp: App {
@StateObject non-public var retailer = SpaceStore()
var physique: some Scene {
WindowGroup {
ContentView()
.environmentObject(retailer)
}
}
}
And the RowView
is sort of the identical as ItemView
besides identify so I omitted it.
Right here is the bizarre issues throughout debugging:
- delete contained in the
ContentView
, it is okay - delete within the
ItemView
for only one merchandise, it is okay - delete within the
RowView
(insideForEach
), boooooom~
P.S.:
- Whereas I import the
RowView
, delete motion of 1&2 flip to be crashed too. - Information was efficiently deleted regardless that crashed after that. So I suppose that the crash was occurred throughout the rerendering.
Then I changed the @EnvironmentObject var retailer: SpaceStore
with let retailer: SpaceStore
in RowView
and the whole lot appears to be working nicely.
Ultimately, I attempted to wrap the delete motion in a confirmationDialog
like this:
.confirmationDialog("", isPresented: $ifShowSheetOfSettings) {
Button("delete") {
retailer.delete(area)
}
}
It crashed once more.
I hope somebody might help me to determine and level out the reason for the crash which is a very powerful.