gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 19:21:05 38 4
gpt4 key购买 nike

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

问题

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

我尝试过的:

  1. Asperi approach - 我可以在 .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 的一部分,那么它不会认为第三个代码块( View 一)依赖于它,并且如果依赖项没有更改,则 View 不会更新。

尝试this方法。

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

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

关于ios - FetchedResults 不会触发和 SwiftUI 更新,但上下文会成功保存它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61843543/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com