SwiftUI - how to update data with fetchRequest in init

So, I found a way of solving my problem.

What was the problem?

The View was not updating because I wasn't using FetchRequest property wrapper, because I need a instance variable in that FetchRequest. So I need to do the Fetching inside my Init() method. But what I did was, I just fetched my items once in the init() and that won't be updated unless the parent with is reloaded.

How to solve it without annoying parent update?

Instead of doing a manual fetch only once in the init() I used a FetchRequest and initialized it in the init(), so it still behaves as FetchRequest property wrapper, like an Observable Object.

I declared it like that:

@FetchRequest var articleRows : FetchedResults<Article>

And inside the init()

//Here in my predicate I use self.type variable 
var predicate = NSPredicate(format: "type == %d", self.type)

//Intialize the FetchRequest property wrapper
self._articleRows = FetchRequest(entity: Article.entity(), sortDescriptors: [], predicate: predicate)

Assuming you have your managedObjectContext set up as such;

@Environment(\.managedObjectContext) var moc

then I believe this solution might work for you.

func deleteArticle(at index: IndexSet) {
    for i in index {
        // pull the article from the FetchRequest
        let article = articleRows[i]
        moc.delete(article)
    }
    // resave to CoreData
    try? moc.save()
}

call that method at the end of your ForEach block with;

.onDelete(perform: deleteArticle)

That said I am not familiar with the way you are doing the fetch request so you made need to do some tweaking.

  • Dan