【问题标题】:How to ForEach in SwiftUI a NSOrderedSet from FetchedResults (CoreData)如何在 SwiftUI 中从 FetchedResults (CoreData) 中获取 NSOrderedSet
【发布时间】:2020-05-14 17:36:28
【问题描述】:

我正在尝试在 SwiftUI 中使用 ForEach,而我的 NSOrderedSet 来自 FetchedResult。 已经尝试过以下代码(来自response

withChilds 是定义的关系(核心数据 - 一张卡片有很多孩子)。

卡内:

@NSManaged public var withChilds: NSOrderedSet?

我的查看代码

struct Test: View {
        @FetchRequest(entity: Card.entity(),
                  sortDescriptors: [],
                  predicate: nil)
    var cards: FetchedResults<Card>

    var body: some View {

        VStack {

            Text("count: \(cards[0].withChilds?.count)") //first entity on purpose

            ScrollView {
                ForEach(cards){  card in
                    ForEach(Array(card.withChilds!.set), id: \.self) { child in //**ERROR**
                        //Text("someText: \(child.text1)")
                    }   
                }
            }
        }
    }
}

错误代码

【问题讨论】:

    标签: swift core-data swiftui nsorderedset


    【解决方案1】:

    突出显示的错误是因为ForEach中没有指定视图,所以如果要定义一些静态的东西,比如

    ForEach(Array(card.withChilds!.set), id: \.self) { child in 
            Text("Just test")
        }   
    

    应该没有错误(用 Xcode 11.4 测试)

    但是没有指定 NSOrderedSet 里面是什么,所以如果假设它是 Child 类的实例,那么下面的测试可以工作

    ForEach(Array(card.withChilds!.set), id: \.self) { child in 
            Text("someText: \((child as! Child).text1)")
        }   
    

    【讨论】:

      猜你喜欢
      • 2020-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-20
      • 1970-01-01
      • 2020-03-04
      • 2020-12-09
      相关资源
      最近更新 更多