SwiftUI在FetchRequest

时间:2019-11-09 21:34:15

标签: ios swift core-data swiftui

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

1 个答案:

答案 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