Post

Replies

Boosts

Views

Activity

Signal SIGABRT on accessing values from SwiftData query
I work on an iOS app using SwiftUI and SwiftData. I added a computed property to one of my models - Parent - that uses relationship - array of Child models - data and I started getting strange problems. Let me start with models: @Model final class Parent { var name: String @Relationship(deleteRule: .cascade, inverse: \Child.parent) var children: [Child]? = [] var streak: Int { // Yes, I know that's not optimal solution for such counter ;) guard let children = children?.sorted(using: SortDescriptor(\.date, order: .reverse)) else { return 0 } var date = Date.now let calendar = Calendar.current for (index, child) in children.enumerated() { if !calendar.isDate(child.date, inSameDayAs: date) { return index } date = calendar.date(byAdding: .day, value: -1, to: date) ?? .now } return children.count } init(name: String) { self.name = name } } @Model final class Child { var date: Date @Relationship(deleteRule: .nullify) var parent: Parent? init(date: Date, parent: Parent) { self.date = date self.parent = parent } } At first everything works as expected. The problem arises once I try to remove one of child from the parent instance. I remove the value from context and save changes without any problems, at least not ones that can be caught by do { } catch. But instead of refreshing UI I get an signal SIGABRT somewhere inside SwiftData internals that points to the line where I'm trying (inside View body) get a child from a Query: struct LastSevenDaysButtons: View { @Environment(\.modelContext) private var modelContext @Query private var children: [Child] private let dates: [Date] private let parent: Parent init(for parent: Parent) { self.parent = parent var lastSevenDays = [Date]() let calendar = Calendar.current let firstDate = calendar.date(byAdding: .day, value: -6, to: calendar.startOfDay(for: .now)) ?? .now var date = firstDate while date <= .now { lastSevenDays.append(date) date = calendar.date(byAdding: .day, value: 1, to: date) ?? .now } dates = lastSevenDays let parentId = parent.persistentModelID _children = Query( filter: #Predicate { $0.parent?.persistentModelID == parentId && $0.date >= firstDate }, sort: [SortDescriptor(\Child.date, order: .reverse)], animation: .default ) } var body: some View { VStack { HStack(alignment: .top) { ForEach(dates, id: \.self) { date in // Here is the last point on stack from my code that I see let child = children.first { $0.date == date } Button { if let child { modelContext.delete(child) } else { modelContext.insert(Child(date: date, parent: parent)) } do { try modelContext.save() } catch { print("Can't save changes for \(parent.name) on \(date.formatted(date: .abbreviated, time: .omitted)): \(error.localizedDescription)") } } label: { Text("\(date.formatted(date: .abbreviated, time: .omitted))") .foregroundStyle(child == nil ? .red : .blue) } } } } } } The LastSevenDaysButtons View is kind of deep in a View hierarchy: RootView -> ParentList -> ParentListItem -> LastSevenDaysButtons However once I move insides of ParentList to RootView application works just fine, although I see and warning: === AttributeGraph: cycle detected through attribute 6912 ===. What could be that I do wrong in here? I believe it must something I'm missing here, but after 2 days of debug, trial and errors, I can't think clearly anymore. Here is the minimal repro I managed to create: Signal SIGABRT on accessing values from SwiftData query
3
0
763
Feb ’25
Fatal error on rollback after delete
I encountered an error when trying to rollback context after deleting some model with multiple one-to-many relationships when encountered a problem later in a deleting method and before saving the changes. Something like this: do { // Fetch model modelContext.delete(model) // Do some async work that potentially throws try modelContext.save() } catch { modelContext.rollback() } When relationship is empty - the parent has no children - I can safely delete and rollback with no issues. However, when there is even one child when I call even this code: modelContext.delete(someModel) modelContext.rollback() I'm getting a fatal error: SwiftData/ModelSnapshot.swift:46: Fatal error: Unexpected backing data for snapshot creation: SwiftData._FullFutureBackingData<ChildModel> I use ModelContext from within the ModelActor but using mainContext changes nothing. My ModelContainer is quite simple and problem occurs on both in-memory and persistent storage, with or without CloudKit database being enabled. I can isolate the issue in test environment, so the model that's being deleted (or any other) is not being accessed by any other part of the application. However, problem looks the same in the real app. I also changed the target version of iOS from 18.0 to 26.0, but to no avail. My models look kind of like this: @Model final class ParentModel { var name: String @Relationship(deleteRule: .cascade, inverse: \ChildModel.parent) var children: [ChildModel]? init(name: String) { self.name = name } } @Model final class ChildModel { var name: String @Relationship(deleteRule: .nullify) var parent: ParentModel? init(name: String) { self.name = name } } I tried many approaches that didn't help: Fetching all children (via fetch) just to "populate" the context Accessing all children on parent model (via let _ = parentModel.children?.count) Deleting all children reading models from parent: for child in parentModel.children ?? [] { modelContext.delete(child) } Deleting all children like this: let parentPersistentModelID = parentModel.persistentModelID modelContext.delete(model: ChildModel.self, where: #Predicate { $0.parent.persistentModelID == parentPersistentModelID }, includeSubclasses: true) Removing @Relationship(deleteRule: .nullify) from ChildModel relationship definition I found 2 solution for the problem: To manually fetch and delete all children prior to deleting parent: let parentPersistentModelID = parentModel.persistentModelID for child in try modelContext.fetch(FetchDescriptor<ChildModel>(predicate: #Predicate { $0.parent.persistentModelID == parentPersistentModelID })) { modelContext.delete(child) } modelContext.delete(parentModel) Trying to run my code in child context (let childContext = ModelContext(modelContext.container)) All that sounds to me like a problem deep inside Swift Data itself. The first solution I found, fetching potentially hundreds of child models just to delete them in case I might need to rollback changes on some error, sounds like awful waste of resources to me. The second one however seems to work fine has that drawback that I can't fully test my code. Right now I can wrap the context (literally creating class that holds ModelContext and calls its methods) and in tests for throwing methods force them to throw. By creating scratch ModelContext I loose that possibility. What might be the real issue here? Am I missing something?
2
0
56
9h
Signal SIGABRT on accessing values from SwiftData query
I work on an iOS app using SwiftUI and SwiftData. I added a computed property to one of my models - Parent - that uses relationship - array of Child models - data and I started getting strange problems. Let me start with models: @Model final class Parent { var name: String @Relationship(deleteRule: .cascade, inverse: \Child.parent) var children: [Child]? = [] var streak: Int { // Yes, I know that's not optimal solution for such counter ;) guard let children = children?.sorted(using: SortDescriptor(\.date, order: .reverse)) else { return 0 } var date = Date.now let calendar = Calendar.current for (index, child) in children.enumerated() { if !calendar.isDate(child.date, inSameDayAs: date) { return index } date = calendar.date(byAdding: .day, value: -1, to: date) ?? .now } return children.count } init(name: String) { self.name = name } } @Model final class Child { var date: Date @Relationship(deleteRule: .nullify) var parent: Parent? init(date: Date, parent: Parent) { self.date = date self.parent = parent } } At first everything works as expected. The problem arises once I try to remove one of child from the parent instance. I remove the value from context and save changes without any problems, at least not ones that can be caught by do { } catch. But instead of refreshing UI I get an signal SIGABRT somewhere inside SwiftData internals that points to the line where I'm trying (inside View body) get a child from a Query: struct LastSevenDaysButtons: View { @Environment(\.modelContext) private var modelContext @Query private var children: [Child] private let dates: [Date] private let parent: Parent init(for parent: Parent) { self.parent = parent var lastSevenDays = [Date]() let calendar = Calendar.current let firstDate = calendar.date(byAdding: .day, value: -6, to: calendar.startOfDay(for: .now)) ?? .now var date = firstDate while date <= .now { lastSevenDays.append(date) date = calendar.date(byAdding: .day, value: 1, to: date) ?? .now } dates = lastSevenDays let parentId = parent.persistentModelID _children = Query( filter: #Predicate { $0.parent?.persistentModelID == parentId && $0.date >= firstDate }, sort: [SortDescriptor(\Child.date, order: .reverse)], animation: .default ) } var body: some View { VStack { HStack(alignment: .top) { ForEach(dates, id: \.self) { date in // Here is the last point on stack from my code that I see let child = children.first { $0.date == date } Button { if let child { modelContext.delete(child) } else { modelContext.insert(Child(date: date, parent: parent)) } do { try modelContext.save() } catch { print("Can't save changes for \(parent.name) on \(date.formatted(date: .abbreviated, time: .omitted)): \(error.localizedDescription)") } } label: { Text("\(date.formatted(date: .abbreviated, time: .omitted))") .foregroundStyle(child == nil ? .red : .blue) } } } } } } The LastSevenDaysButtons View is kind of deep in a View hierarchy: RootView -> ParentList -> ParentListItem -> LastSevenDaysButtons However once I move insides of ParentList to RootView application works just fine, although I see and warning: === AttributeGraph: cycle detected through attribute 6912 ===. What could be that I do wrong in here? I believe it must something I'm missing here, but after 2 days of debug, trial and errors, I can't think clearly anymore. Here is the minimal repro I managed to create: Signal SIGABRT on accessing values from SwiftData query
Replies
3
Boosts
0
Views
763
Activity
Feb ’25
Fatal error on rollback after delete
I encountered an error when trying to rollback context after deleting some model with multiple one-to-many relationships when encountered a problem later in a deleting method and before saving the changes. Something like this: do { // Fetch model modelContext.delete(model) // Do some async work that potentially throws try modelContext.save() } catch { modelContext.rollback() } When relationship is empty - the parent has no children - I can safely delete and rollback with no issues. However, when there is even one child when I call even this code: modelContext.delete(someModel) modelContext.rollback() I'm getting a fatal error: SwiftData/ModelSnapshot.swift:46: Fatal error: Unexpected backing data for snapshot creation: SwiftData._FullFutureBackingData<ChildModel> I use ModelContext from within the ModelActor but using mainContext changes nothing. My ModelContainer is quite simple and problem occurs on both in-memory and persistent storage, with or without CloudKit database being enabled. I can isolate the issue in test environment, so the model that's being deleted (or any other) is not being accessed by any other part of the application. However, problem looks the same in the real app. I also changed the target version of iOS from 18.0 to 26.0, but to no avail. My models look kind of like this: @Model final class ParentModel { var name: String @Relationship(deleteRule: .cascade, inverse: \ChildModel.parent) var children: [ChildModel]? init(name: String) { self.name = name } } @Model final class ChildModel { var name: String @Relationship(deleteRule: .nullify) var parent: ParentModel? init(name: String) { self.name = name } } I tried many approaches that didn't help: Fetching all children (via fetch) just to "populate" the context Accessing all children on parent model (via let _ = parentModel.children?.count) Deleting all children reading models from parent: for child in parentModel.children ?? [] { modelContext.delete(child) } Deleting all children like this: let parentPersistentModelID = parentModel.persistentModelID modelContext.delete(model: ChildModel.self, where: #Predicate { $0.parent.persistentModelID == parentPersistentModelID }, includeSubclasses: true) Removing @Relationship(deleteRule: .nullify) from ChildModel relationship definition I found 2 solution for the problem: To manually fetch and delete all children prior to deleting parent: let parentPersistentModelID = parentModel.persistentModelID for child in try modelContext.fetch(FetchDescriptor<ChildModel>(predicate: #Predicate { $0.parent.persistentModelID == parentPersistentModelID })) { modelContext.delete(child) } modelContext.delete(parentModel) Trying to run my code in child context (let childContext = ModelContext(modelContext.container)) All that sounds to me like a problem deep inside Swift Data itself. The first solution I found, fetching potentially hundreds of child models just to delete them in case I might need to rollback changes on some error, sounds like awful waste of resources to me. The second one however seems to work fine has that drawback that I can't fully test my code. Right now I can wrap the context (literally creating class that holds ModelContext and calls its methods) and in tests for throwing methods force them to throw. By creating scratch ModelContext I loose that possibility. What might be the real issue here? Am I missing something?
Replies
2
Boosts
0
Views
56
Activity
9h