SwiftUI use relationship predicate with struct parameter in FetchRequest

梦想与她 提交于 2020-04-16 04:01:25

问题


How do I do use @FetchRequest with a parameter passed to 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>
    ...

I have todoList set up as a One relationship of TodoItem via TodoList.

It is giving me the error:

Cannot use instance member 'todoList' within property initializer; property initializers run before 'self' is available

How do I do a @FetchRequest with this relationship if I can't use it in the initializer? Also, should I be using todoList.objectID somewhere here instead?


回答1:


Figured it out:

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)
    )
}

Thanks to similar answers here: SwiftUI View and @FetchRequest predicate with variable that can change



来源:https://stackoverflow.com/questions/58783711/swiftui-use-relationship-predicate-with-struct-parameter-in-fetchrequest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!