TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

@FetchRequest does not update View until app restarts

Forums > SwiftUI

Hi, I have 2 views in a ToDos app, one view allows the user to add new ToDos and mark them as completed and another shows a calendar that allows the user to see all the ToDos that they might have completed on any given day. A many to one relationship exists between the ToDo entity and the DayOfYear entity. When the user taps on the ToDo Complete button I update the completedDay_ relationship under ToDo in Core Data. When I immediately switch to the calendar view FetchRequest doesn't contain anything even though I have context.save() immediately after updating the relationship. But when I restart the app, the calendar view shows the Completed Todo correctly. Am I doing something wrong with FetchRequest?

do {
    let today = DayOfYear.withDate(convertStringToDate(day), context: context)
    todo.completedDay_ = today
    try self.context.save()
} catch {
    print("Error saving managed object context: \(error)")
}
extension DayOfYear {
    static func withDate(_ day: Date, context: NSManagedObjectContext) -> DayOfYear {
        let request = fetchRequest(NSPredicate(format: "date = %@", day as CVarArg))
        let days = (try? context.fetch(request)) ?? []
        if let day = days.first {
            return day
        } else {
            let newDay = DayOfYear(context: context)
            newDay.date = day
            return newDay
        }
    }
 }
@FetchRequest(entity: DayOfYear.entity(), sortDescriptors: [], predicate: NSPredicate(format: "date >= %@ AND date <= %@", Date().startOfMonth() as CVarArg, Date() as CVarArg)) var daysOfYear: FetchedResults<DayOfYear>

Text("Completed ToDos").font(.title)
    .onAppear {
        print(self.daysOfYear)
        // prints empty until I restart the app
    }

3      

Seems like a xcode bug, Im facing this issue as well, not sure about the actual reason, Im also facing weird issues with @State variables where the values dont update instantly and always returns nil

2      

Hacking with Swift is sponsored by Superwall.

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn More

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.