如何解决父对象
我有两个Core-Data实体。一种叫做“程序”,另一种叫做“运动”。程序与运动有一对多的关系。我在另一个视图中将“练习”添加到程序中。 我有一个列出了所有程序的视图,并有一个指向该视图的导航链接。
在此视图中,我想列出我之前分配给程序的所有练习。但是,如果尝试此代码,则会收到错误消息:通用结构'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
可以遍历该集合。
例如,Swift的Array
符合RandomAccessCollection
协议,因此您可以使用数组。
我建议您阅读https://github.com/awsdocs/elastic-beanstalk-samples/blob/main/configuration-files/aws-provided/instance-configuration/java-increase-file-descriptors.config或Swift documentation中的收藏集。
可能有几种方法可以实现解决方案,但也许最简单的方法如下...
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!)
}
}
}
}
,
假设您尚未将“多对多关系”的排列方式更改为“有序”,则ProgramDetail.exercise
是NSSet?
。
您可以定义一个计算属性,以将其转换为Exercise
的数组:
extension Program {
var exerciseArray: [Exercise] {
let sortDescriptor = NSSortDescriptor(key: "name",ascending: true)
return exercise?.sortedArray(using: [sortDescriptor]) as? [Exercise] ?? [Exercise]()
}
}
现在在ProgramView
中,您可以使用Array创建列表,如下所示:
List {
ForEach(programDetail.exerciseArray,id: \.self) { exercise in
Text("\(exercise.name ?? "")")
}
}
如果锻炼是有序关系,则ProgramDetail.exercise
将是NSOrderedSet?
。
在这种情况下,exerciseArray的定义甚至更简单:
var exerciseArray: [Exercise] {
return exercise?.array as? [Exercise] ?? [Exercise]()
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。