CoreData:键值观察关系NSSet元素的属性

时间:2019-11-28 10:29:30

标签: core-data key-value-observing nsoutlineview

我有一个Garage实体,其中包含几个Car(一对多关系)。 汽车具有price: NSNumber属性。

我通过NSTreeController在NSOutlineView中显示数据。 群组行代表Garage,带有标签,标签的值是车库中所有汽车的总值。

组内的一行代表一辆汽车。

当我更改汽车的价格(通过编辑或单击按钮)时,会更新汽车行,但不会更新车库组行。但是,当我添加或删除汽车时,车库行中的总值会更新。

这是我的课程:

public class Garage: NSManagedObject {

    @NSManaged public var cars: NSSet?    

    public override class func keyPathsForValuesAffectingValue(forKey key: String) -> Set<String> {
        let mutableSet = NSMutableSet(set: super.keyPathsForValuesAffectingValue(forKey: key))
        if key == "totalValueGarage" {
            mutableSet.add("cars")
        }
        return mutableSet as! Set<String>
    }
}
    /// Total value of the garage. Bound to the NSOutlineView group row.
    @objc dynamic var totalValue: NSNumber {
        var toReturn: NSNumber = NSNumber(value: 0.0)
        if let cars = self.cars {
            for case let car in cars {
                toReturn = NSNumber(value: (toReturn.doubleValue + car.price.doubleValue))               
            }
        }
        return toReturn
    }
public class Car: NSManagedObject {

    @NSManaged public var price: NSNumber?
    @NSManaged public var garage: Garage?

    public override class func keyPathsForValuesAffectingValue(forKey key: String) -> Set<String> {
        let mutableSet = NSMutableSet(set: super.keyPathsForValuesAffectingValue(forKey: key))
        if key == "price" {
            mutableSet.add("garage") // Let the system know that garage is affected by the price value
        }
        return mutableSet as! Set<String>
    }

}

更改汽车价格时,如何确保OutlineView的组行得到更新?

我尝试过的事情

  • 手动调用garage.willChangeValueForKey(“ cars”)和garage.willChangeValueForKey(“ cars”)。这很丑陋,并且撤消更改不会传播更改。撤消时,我还必须触发这些通知。
  • 正在调用outlineView.reloadItem(item:Any?),但是它不起作用。此外,它不如使用KVO优雅。

感谢您的建议!

0 个答案:

没有答案