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

coc*_*ner 6 iphone core-data ios swiftui

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

问题

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

我试过的:

  1. Asperi 方法- 我可以在 .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
Run Code Online (Sandbox Code Playgroud)
//Core Data "Card"
extension Card :Identifiable{

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Card> {
        return NSFetchRequest<Card>(entityName: "Card")
    }

    //...
    @NSManaged public var id: String
    //....

}
Run Code Online (Sandbox Code Playgroud)
//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)
}
Run Code Online (Sandbox Code Playgroud)

Asp*_*eri 1

如果第一个代码块是 ObservableObject 的一部分,那么它看起来不会依赖于第三个代码块(视图一),并且如果依赖项没有更改,则视图不会更新。

尝试这种方法。

但是,如果存在未提供的依赖项,则将保存和发布者的顺序更改为

try context.save()
self.objectWillChange.send()
Run Code Online (Sandbox Code Playgroud)