-3

Error: Cannot use instance member 'date' within property initializer; property initializers run before 'self' is available

I want to use dynamic date when using filter. But it gives an error as I mentioned above. How can we solve this? Can you help me.

@State private var date = Date()
    
    @Environment(\.managedObjectContext) var moc
    @FetchRequest(
        entity: Tasks.entity(),
        sortDescriptors: [NSSortDescriptor(keyPath: \Tasks.taskDate, ascending: false)],
        predicate: NSPredicate(format: "taskDate == %@", date.format("YYYY-MM-dd"))
    ) var tasks: FetchedResults<Tasks>
  • Does this answer your question? [SwiftUI View and @FetchRequest predicate with variable that can change](https://stackoverflow.com/questions/57871088/swiftui-view-and-fetchrequest-predicate-with-variable-that-can-change) In particular the answer by malhal – flanker Aug 17 '23 at 19:22

1 Answers1

0

I added init and it worked. But I need to fetchrequest again when date changes.

init() {

     self._tasks = FetchRequest(entity: Tasks.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Tasks.taskDate, ascending: false)], predicate: NSPredicate(format: "taskDate == %@", date.format("YYYY-MM-dd")))
}

How can I fetchRequest for changed dates. I wrote the following code, but it gives the following error: Cannot assign to property: 'self' is immutable

.onChange(of: date) { newDate in
                self._tasks = FetchRequest(entity: Tasks.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Tasks.taskDate, ascending: false)], predicate: NSPredicate(format: "taskDate == %@", newDate.format("YYYY-MM-dd")))
}