问题描述
我尝试使用从嵌套列表中的 Core Data 获取的数据,但是当我添加“children: .listofTasksArray”时,会显示以下错误: “关键路径值类型'[listofTasks]?'无法转换为上下文类型“FetchedResults?” 这是核心数据文件
extension listofTasks {
@nonobjc public class func fetchRequest() -> NSFetchRequest<listofTasks> {
return NSFetchRequest<listofTasks>(entityName: "listofTasks")
}
@NSManaged public var addedDate: Date?
@NSManaged public var color: String?
@NSManaged public var favoriteIndex: Int16
@NSManaged public var icon: String?
@NSManaged public var id: UUID?
@NSManaged public var index: Int16
@NSManaged public var isArchived: Bool
@NSManaged public var isFavorite: Bool
@NSManaged public var isLocked: Bool
@NSManaged public var title: String?
@NSManaged public var isList: Bool
@NSManaged public var origin: listofTasks?
@NSManaged public var subLists: NSSet?
// The wrapped items
public var wrappedAddedDate: Date {
return addedDate ?? Date()
}
// To convert the color from "String" to "Color" type
public var wrappedColor: Color {
return Color(colorName: color ?? "blue")
}
public var wrappedIcon: String {
return icon ?? "ellipsis.circle.fill"
}
public var wrappedId: UUID {
return id ?? UUID()
}
public var wrappedTitle: String {
return title ?? "UnkNown Title"
}
public var listofTasksArray: [listofTasks]? {
let set = subLists as? Set<listofTasks> ?? nil
return set?.sorted { // sort by index
$0.index > $1.index
}
}
}
这是我用来获取数据并在列表中使用它的列表代码,尝试使用 listofTasks 属性“listofTasksArray”作为列表的子项来制作嵌套列表。
struct ListsView: View {
@FetchRequest(entity: listofTasks.entity(),sortDescriptors: [NSSortDescriptor(keyPath: \listofTasks.index,ascending: true)],animation: .default) private var lists: FetchedResults<listofTasks>
var body: some View {
List(lists,children: \.listofTasksArray,rowContent: { Text($0.wrappedTitle) })
}
}
解决方法
数据容器的类型应该是相同的,所以尝试将 FetchedResults
包装到一个数组中,比如(可能需要对选项做一些调整)
var body: some View {
List(Array(lists),children: \.listofTasksArray) {
Text($0.wrappedTitle
}
}