Updating @FetchRequest which uses a predicate with Swift 5/ SwiftUI

Viewed 236

Firsly, I have tried to search online for this issue, and while similar ones show up, I've not found a solution.

I have been using some SwiftUI tutorials to get started with CoreData and the @FetchResults property wrapper. I have two wrappers, one which returns all the results and one which would filter on a predicate.

When new data is added to the CoreData model, the result which collects everything is automatically updated (and displayed in a list for debugging). However, the other wrapper does not update and as far as I can tell, this is due to the use of the predicate in the construction. When I reload my application, this second wrapper starts returning results, which makes me believe that the @FetchResults is not recognising there is a change and updating its results.

My code is quite straightforward:

struct ContentView: View {
    @Environment(\.managedObjectContext) private var viewContext
    
    // Fetch Request
    @FetchRequest(sortDescriptors: []) private var Object : FetchedResults<Object>
    @FetchRequest(sortDescriptors: [], predicate: NSPredicate(format: "datetime >= %@ AND datetime < %@ AND type == %@", Calendar.current.startOfDay(for: Date()) as NSDate, Date() as NSDate, "Test")) private var ObjectsToday : FetchedResults<Object>

 var body: some View {

        ...

I have a button which is just populating the CoreData, and when I add new data, this is displayed in the Objects results but does not appear in the ObjectsToday list. Is there a technique to reload this FetchRequest? I can see that there is self._ObjectsToday.Update() but I cannot access this due to it being immutable.

I am using Xcode 11.3.1 (not the latest and greatest) and I cannot find any example on how to overcome this. I could avoid using this additional FetchRequest by manually filtering on my full set of results, to identify the data I need to update, but this seems excessive when these tools exist.

Just to reiterate, when I reload the app, this result becomes populated which is what makes me think something is missing in an automatic update somewhere.

Many thanks!

0 Answers
Related