我有一个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的组行得到更新?
我尝试过的事情
感谢您的建议!