6

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:

  1. Asperi approach - I can print out the correct new value in .onReceive but the UI doesn't update
  2. Using self.objectWillChange.send() before context.save() - didn't work either
  3. 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)
}
cocos2dbeginner
  • 2,185
  • 1
  • 31
  • 58

1 Answers1

1

If first code block is a part of ObservableObject, then it does not look that third block, view one, depends on it, and if there is no changes in dependencies, view is not updated.

Try this approach.

But if there are dependencies, which are just not provided then change order of save and publisher as

try context.save()
self.objectWillChange.send()
Asperi
  • 228,894
  • 20
  • 464
  • 690
  • I have setup an EnvironmentObject which is stuck on the main view. In there I am changing the data and saving the context. But context ist just let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext – cocos2dbeginner May 17 '20 at 06:34
  • Got it working in this order - now the UI updates: 1. save the context 2. reset the context 3. self.objectWillChange.send() – cocos2dbeginner May 17 '20 at 06:39