以下是 Aaron Hillegas 的书 cocoa programming for 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 时不会被释放?