1

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

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)")
                    }   
                }
            }
        }
    }
}

错误代码 在此处输入图像描述

4

1 回答 1

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-05-14T18:19:41.393 回答