I have run into this SwiftData issue in multiple projects and have been able to replicate it by building off of the default SwiftData launch project.
The original Item class:
class Item {
var timestamp: Date
init(timestamp: Date) {
self.timestamp = timestamp
}
}
New MyItem class to replicate the error. Notice I nest an Item object inside MyItem:
class MyItem {
var name: String
var item: Item
init(name: String, item: Item) {
self.name = name
self.item = item
}
}
I then build off of the default view for a SwiftData project. When the '+' button is pressed, a new list item for both Item and MyItem should appear in their appropriate sections.
@Environment(\.modelContext) private var modelContext
@Query private var items: [Item]
@Query private var myItems: [MyItem]
var body: some View {
NavigationSplitView {
List {
Section("All Items") {
ForEach(items) { item in
NavigationLink {
Text("Item at \(item.timestamp, format: Date.FormatStyle(date: .numeric, time: .standard))")
} label: {
Text(item.timestamp, format: Date.FormatStyle(date: .numeric, time: .standard))
}
}
}
Section("My Items") {
ForEach(myItems) { myItem in
NavigationLink {
Text("Item at \(myItem.item.timestamp, format: Date.FormatStyle(date: .numeric, time: .standard))")
} label: {
HStack {
Text(myItem.name)
Spacer()
Text(myItem.item.timestamp, format: Date.FormatStyle(date: .numeric, time: .standard))
}
}
}
}
}
.toolbar {
ToolbarItem {
Button(action: addItem) {
Label("Add Item", systemImage: "plus")
}
}
}
} detail: {
Text("Select an item")
}
}
private func addItem() {
withAnimation {
let newItem = Item(timestamp: Date())
modelContext.insert(newItem)
let newMyItem = MyItem(name: "Test", item: newItem)
modelContext.insert(newMyItem)
}
}
}
The app crashes and I get the following error when I attempt to click the '+' button (which should create a new Item and MyItem in the modelContext:
Thread 1: "Illegal attempt to establish a relationship 'item' between objects in different contexts (source = <NSManagedObject: 0x600002166940> (entity: MyItem; id: 0x600000298240 <x-coredata:///MyItem/t2D4951EB-0D2F-44B1-AF8C-5A1BB11659F53>; data: {\n item = nil;\n name = Test;\n}) , destination = <NSManagedObject: 0x600002174000> (entity: Item; id: 0x600000232440 <x-coredata:///Item/t2D4951EB-0D2F-44B1-AF8C-5A1BB11659F52>; data: {\n timestamp = "2023-10-04 18:21:21 +0000";\n}))"
Can anyone help me understand the new SwiftData framework in this regard? I am still new to SwiftUI.