SwiftUI在FetchRequest

如何将@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>
    ...

我通过todoListOne设置为TodoItem的{​​{1}}关系。

它给了我错误:

  

不能在属性初始化程序中使用实例成员“ todoList”;属性初始化程序在“自我”可用之前运行

如果无法在初始化程序中使用它,该如何处理TodoList?另外,我应该在这里的某个地方使用@FetchRequest吗?

qianqianyouer 回答:SwiftUI在FetchRequest

想通了:

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

本文链接:https://www.f2er.com/3131200.html

大家都在问