FetchedResults 不会触发和 SwiftUI 更新,但上下文成功保存它

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

我正在尝试通过 NSManagedObject 更新我的核心数据中的属性。我一更新它,就保存上下文,它就成功保存了。

问题

上下文保存后,UI (SwiftUI) 不会用新值更新它。如果我将一个全新的 Children 添加到核心数据(插入)中,UI 会更新。

我尝试了什么:

  1. - 我可以在 .onReceive 中打印出正确的新值,但 UI 不会更新
  2. 在 context.save() 之前使用 self.objectWillChange.send() - 也没有用
  3. 将 Int16 更改为 String,因为我推测 Int16 不知何故不可观察?也没用

这是 SwiftUI 的错误吗? 现状

//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)
}

如果第一个代码块是 ObservableObject 的一部分,那么它不会查看第三个块,即视图一,依赖于它,如果依赖项没有变化,则视图不会更新。

尝试方法。

但是如果有依赖项,只是没有提供,则更改保存和发布者的顺序为

try context.save()
self.objectWillChange.send()