【问题标题】:SwfitUI 2.0 Xcode 12 How To Update A Single Attribute Of A Core Data EntitySwiftUI 2.0 Xcode 12 如何更新核心数据实体的单个属性
【发布时间】:2021-01-21 04:40:49
【问题描述】:

我正在尝试在我的视图模型中实现一个重置方法,该方法将在按钮操作的视图中调用,因此视图将得到更新和持久化

这是我的视图模型中发布的实体的属性

var viewContext: NSManagedObjectContext { PersistenceController.shared.container.viewContext }

@Published var price: Double
@Published var qty: Int
@Published var subtotal: Double

这是我尝试过的 resetAllCounters 方法我知道这是错误的方法我只想将 qty 重置为 0 并更新所有计数器

    func resetAllSubtotals(){
    let allCounters: NSFetchRequest<WindowCounter> = WindowCounter.fetchRequest()

    do {
        let savedWindowCounters = try self.viewContext.fetch(allCounters)
        
        for counter in savedWindowCounters {
            counter.qty = 0
        }
        
        try self.viewContext.save()
    } catch {
        print(error.localizedDescription)
    }
}

【问题讨论】:

    标签: xcode core-data swiftui


    【解决方案1】:

    使用NSBatchUpdateRequest

    func resetAllSubtotals(){
        let request = NSBatchUpdateRequest(entityName: "WindowCounter")
        request.propertiesToUpdate = ["qty":0]
        request.resultType = .updatedObjectsCountResultType
        
        do {
            let result = try context.execute(request) as! NSBatchUpdateResult
            //This print the number of rows affected/updated
            print(result.result!)
        }catch {
            //Handel Catch here
        }
    }
    
    

    【讨论】:

    • Raja 感谢您的帮助,这对我来说意义重大。这不会更新视图
    • 检查此线程以更新视图:stackoverflow.com/a/60266079/14733292
    • 我确实看过线程我看到他们在谈论更新你的内存对象我只是无法理解如何更新对象
    【解决方案2】:

    我的解决方案是我决定不在视图模型中观察对象,而是只观察实体本身,因为它符合 ObservableObject 然后创建一个子类来处理该方法

     extension NSManagedObjectContext {
      
      func resetAllSubtotals(){
       let allCounters: NSFetchRequest<WindowCounter> = 
       WindowCounter.fetchRequest()
    
       do {
           let savedWindowCounters = try self.fetch(allCounters)
    
           for counter in savedWindowCounters {
               counter.qty = 0
               counter.subtotal = 0
           }
           try self.save()
       } catch {
           print(error.localizedDescription)
       }
    

    } }

    【讨论】:

      猜你喜欢
      • 2012-07-03
      • 1970-01-01
      • 2012-08-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多