Post

Replies

Boosts

Views

Activity

Swift Data Fail to previewivrelationship
Hi! I was trying to develop a todo list app. There are two models: import Foundation import SwiftData @Model class Item { var id: UUID var title: String var detail: String @Relationship(deleteRule: .cascade, inverse: \SubItem.item) var subitems: [SubItem] var isCompleted: Bool var timestamp: Date init(id: UUID = UUID(), title: String = "", detail: String = "", subitems: [SubItem] = [], isCompleted: Bool = false, timestamp: Date = .now) { self.id = id self.title = title self.detail = detail self.subitems = subitems self.isCompleted = isCompleted self.timestamp = timestamp } } @Model class SubItem { var id: UUID var title: String var isCompleted: Bool var item: Item init(id: UUID = UUID(), title: String = "", isCompleted: Bool = false, item: Item) { self.id = id self.title = title self.isCompleted = isCompleted self.item = item } } In a component view, I was trying to preload some sample data in the preview: struct ItemRowView: View { @Bindable var item: Item //...... } #Preview { let schema = Schema([ Item.self, SubItem.self ]) let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: true) let container = try! ModelContainer(for: schema, configurations: [modelConfiguration]) let context = container.mainContext var item: Item = Item(title: "Item title 1", detail: "") var subitem1 = SubItem(title: "subitem 4", item: item) var subitem2 = SubItem(title: "subitem 2", item: item) context.insert(item) context.insert(subitem1) context.insert(subitem2) return ItemRowView(item: item) .modelContainer(container) .padding() } However, item.subitems is always empty in this view. What's wrong?
0
0
250
Feb ’24