【发布时间】:2014-06-22 06:41:35
【问题描述】:
我有一个NSDocument 子类,连接到NSArrayController。作为参考,我正在尝试翻译 Cocoa Programming for Mac OS X Fourth Edition 第 9 章中的示例。
从我之前问过的this question看来,我需要对NSUndoManager使用基于对象的撤消。为了将两个值传递给被调用的方法,我将它们打包到带有两个实例变量的NSObject 子类中。
当通过单击我的应用程序中的按钮调用从 employees 数组中插入和删除的 KVO 方法时,它们按预期工作。
但是,当在撤消操作期间调用removeObjectFromEmployeesAtIndex 时,传入的index 非常超出范围(对于第一行,它似乎总是55,然后索引增加到接下来的几行有数千个)。
如何获得正确的索引来执行撤消操作?
class Document: NSDocument {
var employee_list: Array<Person> = []
var employees: Array<Person> {
get {
return self.employee_list
}
set {
if newValue == self.employee_list {
return
}
self.employee_list = newValue
}
}
func insertObject(person: Person, inEmployeesAtIndex index: Int) {
self.undoManager.registerUndoWithTarget(self, selector: Selector("removeObjectFromEmployeesAtIndex:"), object: index)
if (!self.undoManager.undoing) {
self.undoManager.setActionName("Add Person")
}
employees.insert(person, atIndex: index)
}
func removeObjectFromEmployeesAtIndex(index: Int) {
let person = self.employees[index]
let pair = PersonIndexPair(person: person, index: index)
self.undoManager.registerUndoWithTarget(self, selector: Selector("insertPersonIndexPair:"), object: pair)
if (!self.undoManager.undoing) {
self.undoManager.setActionName("Remove Person")
}
employees.removeAtIndex(index)
}
func insertPersonIndexPair(pair: PersonIndexPair) {
insertObject(pair.person, inEmployeesAtIndex: pair.index)
}
}
编辑:我通过传递一个字符串来解决这个问题,但这似乎很迟钝:
self.undoManager.registerUndoWithTarget(self, selector: Selector("removeObjectFromEmployeesAtStringIndex:"), object: String(index))
//...
func removeObjectFromEmployeesAtStringIndex(index: String) {
if let i = index.toInt() {
removeObjectFromEmployeesAtIndex(i)
}
}
【问题讨论】: