问题
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