SwiftUI 在 FetchRequest 中使用带有结构参数的关系谓词

kdi*_*891 2 core-data ios swift swiftui

如何使用@FetchRequest传递给 a 的参数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>
    ...
Run Code Online (Sandbox Code Playgroud)

我已经todoList设置为via的One关系。TodoItemTodoList

它给了我错误:

不能在属性初始值设定项中使用实例成员“todoList”;属性初始值设定项在 'self' 可用之前运行

@FetchRequest如果我不能在初始化程序中使用它,我该如何处理这种关系?另外,我应该todoList.objectID在这里使用某个地方吗?

kdi*_*891 8

弄清楚了:

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)
    )
}
Run Code Online (Sandbox Code Playgroud)

感谢这里的类似答案:SwiftUI View and @FetchRequest predicate with variable that can change