Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FetchedResults won't trigger and SwiftUI update but the context saves it successfully

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)
}
like image 793
cocos2dbeginner Avatar asked May 16 '20 21:05

cocos2dbeginner


1 Answers

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()
like image 174
Asperi Avatar answered Oct 27 '22 16:10

Asperi