简体   繁体   中英

SwiftUI use relationship predicate with struct parameter in FetchRequest

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM