我有两个核心数据实体。一种叫做“程序”,另一种叫做“运动”。程序与运动有一对多的关系。
我在另一个视图中将“练习”添加到“程序”中。我有一个列出了所有程序的视图,并且有一个导航链接指向该视图。
在此视图中,我想列出我之前分配给程序的所有练习。但是,如果尝试此代码,则会收到错误消息:通用结构'ForEach'要求'Exercise'符合'RandomAccessCollection'。
我是Core Data Relationships的新手,并且认为我可能忘记了在CoreDataClass File中声明某些内容。问题是我找不到这个问题的其他解决方案。
struct ProgramView: View {
@ObservedObject var ProgramDetail: Program
var body: some View {
List {
ForEach(ProgramDetail.exercise!, id: \.self) { exercise in
Text(exercise.name!)
}
}
这将生成所有程序的列表:
struct ProgramList: View {
@Environment(\.managedObjectContext) var viewContext
@FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \Program.date, ascending: false)]) var programFetch: FetchedResults<Program>
var body: some View {
NavigationView {
List {
ForEach(programFetch, id: \.self) { program in
NavigationLink(destination: ProgramView(ProgramDetail: program)) {
Text(program.title!)
}
}
}.navigationBarItems(
trailing:
NavigationLink(destination: CreateProgram()) {
Image(systemName: "plus.circle").font(.system(size: 25))
})
}
}
这是界面的屏幕截图?:
错误消息说明您必须具有随机访问集合,以便ForEach
可以迭代该集合。
例如,SwiftArray
遵循RandomAccessCollection
协议,因此您可以使用数组。
我建议您在Swift文档或Apple的Developer网站上阅读集合。
解决方案可能有几种方法,但也许最简单的方法如下:
struct ProgramView: View {
@ObservedObject var programDetail: Program
@FetchRequest(entity: Exercise.entity(),
sortDescriptors: [NSSortDescriptor(keyPath: \Exercise.name, ascending: true)],
) var allExercises: FetchedResults<Exercise>
var body: some View {
List {
// in this line you create an array of fetched results
// filtered to contain only exercises for programDetail
let exercisesForProgram = allExercises.filter { $0.program == programDetail }
ForEach(exercisesForProgram) { exercise in
Text(exercise.name!)
}
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句