如何使用 SwiftUI 在 CoreData 中的 ForEach 中使用关系?

How can I use relationship in ForEach in CoreData using SwiftUI?

问题已被'hackingwithswift'网站解决

只需按照 link 上的步骤操作即可! “https://www.hackingwithswift.com/books/ios-swiftui/one-to-many-relationships-with-core-data-swiftui-and-fetchrequest”

原问

我想使用[关系]的元素
但是无论我尝试什么,它都不起作用..
有些东西,我错过了,遗憾的是直到现在我才知道那是什么:/

首先,我想展示一下我的核心数据模型和代码。

Core Data Model Image

实体:页面,属性:名称(字符串),关系: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 不显示卡片的属性,因为它们不匹配。
我该如何修复它..?

Card数据已保存在关系中(代码如下)

let card = Card(context: self.moc)
card.title = self.title
card.price = self.doubleValue
selectedPage?.addToToCard(card)

我在这个很棒的 'hackingwithswift' 网站的帮助下解决了这个问题!只需按照 link!

上的步骤操作即可

https://www.hackingwithswift.com/books/ios-swiftui/one-to-many-relationships-with-core-data-swiftui-and-fetchrequest

已编辑:

  1. 转到 .xcdatamodeld 文件

  2. 单击实体 -> Class -> Codezen 到 Manual/None

  3. 编辑器 -> 创建 NSManagedObject 子类

  4. 在页面添加+CoreDataProperties.swift

    public var wrappedName: String {
         name ?? "Unknown Title"
     }
    
     public var cardArray: [Card] {
         let set = toCard as? Set<Card> ?? []
    
         return set.sorted {
             [=10=].wrappedTitle < .wrappedTitle
         }
     }
    
  5. 加入“卡片+CoreDataProperties.swift”

    public var wrappedTitle: String {
         title ?? "Unknown Title"
     }
    
     public var wrappedPrice: Double {
         price
     }
    
  6. 现在你可以像这样使用关系的价值了!

ForEach(pages, id: \.self) { page in
    if whichPage == page {
        ForEach(page.cardArray, id: \.self) { card in
            VStack {
                CardView(price: card.wrappedPrice, title: card.wrappedTitle)
            }
        }
    }
}