目前代码看起来非常粗略:
@NSManaged var property1: NSNumber?
@NSManaged var property2: String?
@NSManaged var property3: NSNumber
@NSManaged var property4: NSNumber?
@NSManaged var property5: Date?
override func setValue(_ value: Any?, ofProperty property: String) -> Bool {
let undoManager = NSDocumentController.shared().currentDocument?.undoManager
if property == "property1" {
undoManager?.registerUndo(withTarget:self, handler: { [oldValue = self.property1] (Node) -> () in
self.property1 = oldValue
})
} else if property == "property2" {
undoManager?.registerUndo(withTarget:self, handler: { [oldValue = self.property2] (Node) -> () in
self.property2 = oldValue
})
} else if property == "property3" {
undoManager?.registerUndo(withTarget:self, handler: { [oldValue = self.property3] (Node) -> () in
self.property3 = oldValue
})
} else if property == "property4" {
undoManager?.registerUndo(withTarget:self, handler: { [oldValue = self.property4] (Node) -> () in
self.property4 = oldValue
})
} else if property == "property5" {
undoManager?.registerUndo(withTarget:self, handler: { [oldValue = self.property5] (Node) -> () in
self.property5 = oldValue
})
}
优化的直接想法是使用KVC,setValue:forKey:
,它将删除我的switch语句(我知道这是一个很大的if / else if块)
但是,这样做会在运行时抛出错误:
[General] [valueForUndefinedKey:]:这个类是 密钥通道不符合密钥值编码。
我以前见过这个,我认为这是因为我的属性是@NSManaged
,并且没有被ivar支持。虽然我不确定
以前有人见过这个,或者知道我可以优化的方法吗?我只是问,因为实际上有超过20个属性,这样做感觉非常糟糕