以下是通过Aaron Hillegas编写的针对OS X的可可编程书​​籍中的撤消功能的代码:

-(void)removeObjectFromEmployeesAtIndex:(NSUInteger)index
{
Person *p = [employees objectAtIndex:index];
NSLog(@"removing %@ from %@", p, employees);
// Add the inverse of this operation to the undo stack
NSUndoManager *undo = [self undoManager]; [[undo prepareWithInvocationTarget:self]  insertObject:p inEmployeesAtIndex:index];

if (![undo isUndoing]) {
  [undo setActionName:@"Remove Person"];
}
[employees removeObjectAtIndex:index];
}


在删除员工时,我们将命令压入撤消堆栈,以将该员工重新插入到阵列中。但是,有什么保证在调用撤消时不会释放p?

最佳答案

通过“ [[[undo prepareWithInvocationTarget:self] insertObject:p inEmployeesAtIndex:index]”创建NSInvocation时,将保留“ p”

10-08 08:21