Cocoa NSUndoManager是否保留其参数?
以下是从Aaron Hillegas的《cocoa programming for OS X》一书中启用撤消的代码:Cocoa NSUndoManager是否保留其参数?,cocoa,memory-management,nsundomanager,Cocoa,Memory Management,Nsundomanager,以下是从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 t
-(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不会被释放呢?'p'将在通过“[[undo prepareWithinLocationTarget:self]insertObject:p InEmployeesIndex:index]”创建NSInvocation时被保留。这是真的。我试着记录保留计数。但在哪里有记录?它不在NsEndomanager或PrepareWithinLocationTarget文档中。它没有明确的文档记录,但基于内存管理的一般规则进行假设。使用引用计数。在这种情况下,如果对象(NSInvocation)希望保留对对象的引用,则需要保留该引用。调用者不在乎,可以在处理完对象后释放它——没有什么不同,例如,在向NSArray添加对象时。[NSArray addObject:]负责保留添加的对象。当[NSArray addObject:]返回时,调用方可以立即释放它。NSInvocation的文档明确指出,除非调用方发送RetainObject消息,否则它不会保留任何对象。在我看来,这是一个文档失败。显然,不是NSInvocation保留了参数,而是[NSEndomanager PrepareWithinLocationTarget:]返回的代理。