I am having some issues using SwiftUI
whith CoreData
.
My app has a list of items coming from a core-data entity.
The initial (template) code -provided by Xcode when starting a project- works.
But problems come when I want to set a predicate in order to select which items ought to be listed.
At this point I can have the app start with a given selection. In other words I am able to set a predicate to begin with.
Problems appear when the predicate should be updated while the app is running to select a different set of items to be listed.
Here is how the code currently looks like:
import SwiftUI
import CoreData
struct ContentView: View {
@Environment(\.managedObjectContext) private var viewContext
.....
@FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: \TheEntity. sortField, ascending: true)],
animation: .default)
private var items: FetchedResults<TheEntity>
@FetchRequest var items: FetchedResults<TheEntity>
.....
init() {
let cntxt = PersistenceController.shared.container. viewContext,
theMedia = HearText.currentMedia(inMOContext: cntxt),
predicate = NSPredicate(format: "media==%@", theMedia)
self._items = FetchRequest(entity: TheEntity.entity(),
sortDescriptors:
[NSSortDescriptor(keyPath: \TheEntity.sortField,
ascending: true)],
predicate: predicate)
}
.....
}
And it is working, except that when currentMedia() returns a different value due to some action inside the app the list is not updated accordingly.
Though I have tried out some solutions, I have at this point nothing working. There must be a way to solve this, but my main problem is that it is impossible to use any instance variable inside init(). Any relevant tip on how to handle this issue would be highly appreciated.