【发布时间】:2021-07-21 15:39:29
【问题描述】:
“hackingwithswift”网站已解决问题
只需按照链接上的步骤操作即可! “https://www.hackingwithswift.com/books/ios-swiftui/one-to-many-relationships-with-core-data-swiftui-and-fetchrequest”
原问
我想使用 [relationship]
的元素
但无论我尝试什么,它都不起作用..
有一些东西,我错过了,遗憾的是我直到现在才知道那会是什么:/
首先,我想展示我的核心数据模型和代码。
实体:页面,属性:名称(字符串),关系:toCard
实体:卡片,属性:title(String),price(Double),关系:toPage
场景:页面有多张卡片
一对多(一页对多张卡片)
ContentView.swift
TabView(selection: self.$pageIndex){
MainPageView()
ForEach(pages, id: \.self) { page in
SubPageView(whichPage: page)
}
}
SubPageView.swift
@Environment(\.managedObjectContext) var moc
@FetchRequest(entity: Page.entity(),
sortDescriptors: [NSSortDescriptor(keyPath: \Page.name, ascending: true),
NSSortDescriptor(keyPath: \Page.toCard, ascending: true)]
) var pages: FetchedResults<Page>
@FetchRequest(entity: Card.entity(),
sortDescriptors: [NSSortDescriptor(keyPath: \Card.title, ascending: true),
NSSortDescriptor(keyPath: \Card.price, ascending: true)]
) var cards: FetchedResults<Card>
var whichPage: FetchedResults<Page>.Element
ForEach(pages, id: \.self) { page in // page: 1번 2번 3번
if whichPage == page {
ForEach(Array(whichPage.toCard! as Set), id: \.self) { relationshipFromToCard in
}
}
问题来了
ForEach(Array(whichPage.toCard! as Set), id: \.self) { item in
CardView(price: item.price, title: item.title ?? "Unknown")
}
我不能在 CardView 中这样使用。
Xcode 不显示卡片的属性,因为它们不匹配。
我该如何解决它..?
卡的数据已经保存在关系中(代码如下)
let card = Card(context: self.moc)
card.title = self.title
card.price = self.doubleValue
selectedPage?.addToToCard(card)
【问题讨论】:
标签: ios swift core-data swiftui relationship