I am trying to update an attribute in my Core Data through an NSManagedObject. As soon as I update it, I save the context and it gets saved successfully.
Problem
After the context saves it, the UI (SwiftUI) won't update it with the new value. If I add a completely new Children into Core Data (insert) the UI gets updated.
What I tried:
- Asperi approach - I can print out the correct new value in .onReceive but the UI doesn't update
- Using self.objectWillChange.send() before context.save() - didn't work either
- Changed the Int16 to String, because I was speculating that somehow Int16 is not observable? Didn't work either
Is this a SwiftUI bug? As-is State
//only updating the data
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let fetchReq = NSFetchRequest<Card>(entityName: "Card") //filter distributorID; should return only one Card
fetchReq.resultType = .managedObjectResultType
fetchReq.predicate = NSPredicate(format: "id == %@", params["id"]!) //I get an array with cards
var cards :[Card] = []
cards = try context.fetch(fetchReq)
//some other functions
cards[0].counter = "3" //
//...
self.objectWillChange.send() //doesn't do anything?
try context.save()
//sucessfully, no error. Data is there if I restart the app and "force" a reload of the UI
//Core Data "Card"
extension Card :Identifiable{
@nonobjc public class func fetchRequest() -> NSFetchRequest<Card> {
return NSFetchRequest<Card>(entityName: "Card")
}
//...
@NSManaged public var id: String
//....
}
//Main SwiftUI - data is correctly displayed on the card
@FetchRequest(entity: Card.entity(),
sortDescriptors: [],
predicate: nil)
var cards: FetchedResults<Card>
List {
ForEach(cards){ card in
CardView(value: Int(card.counter)!, maximum: Int(card.maxValue)!,
headline: card.desc, mstatement: card.id)
}