如何将@FetchRequest
与传递给struct
的参数一起使用?
struct TodoItemView: View {
var todoList: TodoList
@FetchRequest(
entity: TodoItem.entity(),
sortDescriptors: [NSSortDescriptor(key: "order", ascending: true)],
predicate: NSPredicate(format: "todoList == %@", todoList)
) var todoItems: FetchedResults<TodoItem>
...
我通过todoList
将One
设置为TodoItem
的{{1}}关系。
它给了我错误:
不能在属性初始化程序中使用实例成员“ todoList”;属性初始化程序在“自我”可用之前运行
如果无法在初始化程序中使用它,该如何处理TodoList
?另外,我应该在这里的某个地方使用@FetchRequest
吗?
答案 0 :(得分:2)
想通了:
var todoList: TodoList
@FetchRequest var todoItems: FetchedResults<TodoItem>
init(todoList: TodoList) {
self.todoList = todoList
self._todoItems = FetchRequest(
entity: TodoItem.entity(),
sortDescriptors: [NSSortDescriptor(key: "order", ascending: true)],
predicate: NSPredicate(format: "todoList == %@", todoList)
)
}
在此感谢类似的答案:SwiftUI View and @FetchRequest predicate with variable that can change