gpt4 book ai didi

ios - 在 SwiftUI 的 ListView 中使用可识别的对象集

转载 作者:行者123 更新时间:2023-12-01 16:20:06 24 4
gpt4 key购买 nike

我有一个由 DataCore 处理的数据库。我正在尝试检索任何“分配”对象并将其插入到 View 列表中。分配类本身是可识别的,但是在尝试在 View 中创建 List 时出现错误:

Initializer 'init(_:id:rowContent:)' requires that 'Set<NSManagedObject>' conform to 'RandomAccessCollection'
即使对象是可识别的,集合本身是否也是不可识别的?如何在 View 列表中显示集合中的所有对象?
风景:
import SwiftUI

struct AssignmentList: View {


@ObservedObject var assignmentViewModel = assignmentViewModel()

var body: some View {


VStack {


NavigationView {

//**The error is in the following line : **
List(assignmentViewModel.allAssignments, id: \.self) { assignment in

AssignmentRow(assignmentName: assignment.assignmentName, notes: assignment.notes) //This view works by itself and just present the data as text under HStack

}
.navigationBarTitle(Text("Assignments"))
}

Button(action: {


self.assignmentViewModel.retrieveAllAssignments()


}) {

Text("Retrieve")
}
}


}
}
这是作业类:
import Foundation
import CoreData


extension Assignment: Identifiable {

@nonobjc public class func fetchRequest() -> NSFetchRequest<Assignment> {
return NSFetchRequest<Assignment>(entityName: "Assignment")
}

@NSManaged public var id: UUID?
@NSManaged public var assignmentName: String?
@NSManaged public var notes: String?


}
这是使用绑定(bind)连接到 View 的 ViewModel:
class AssignmentViewModel : ObservableObject
{



private var assignmentModel = AssignmentModel()

/*AssignmentModel is a different class, we assume all methods working correctly and it's not a part of the question.*/



@Published var allAssignments : Set<Assignment>



init()
{
allAssignments=[]

}


func retrieveAllAssignment()
{

allAssignments=assignmentModel.retrieveAllAssignments()

}

}

最佳答案

尝试以下

List(Array(assignmentViewModel.allAssignments), id: \.self) { assignment in


关于ios - 在 SwiftUI 的 ListView 中使用可识别的对象集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62643956/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com