I am doing a CoreData fetch inside my init()
method of the View. I am not using FetchRequest in SwiftUI, as I need a predicate based on a parameter which is send to the View aswell. Using that parameter in the @FetchRequest will cause an error, as the variable has not been initialized.
I am doing following fetch Request inside the init()
//FetchRequest
let fetch : NSFetchRequest<Article>
self.articleRows = [Article]()
fetch = Article.fetchRequest() as! NSFetchRequest<Article>
fetch.predicate = NSPredicate(format: "type == %d", self.type)
do {
self.articleRows = try NSManagedObjectContext.current.fetch(fetch)
} catch
{
}
That is working fine. I am displaying all my data inside a ForEach
loop.
ForEach(self.articleRows, id:\.self) { article in
However, when I am deleting an entity from my context I need to refresh the view to display the changes. On delete action I toggle a @State
variable, to refresh the view. That works, however the entity is still inside my Array. Thats due to the fact that init()
is not called again and the fetch request is not made again. If init()
would be called, the deleted entity wouldn't be there anymore.
What is the best approach here? How can I refetch my CoreData entities.
My current solution: I am currently using a Binding
inside my Fetch view. If I make changes I toggle that binding and my parent view reloads. The will cause my child view (fetch View) to reload aswell and the fetch request is made again. Is that the best way? Any simpler solution for that?