NSInvocation
究竟是如何工作的?有没有好的介绍?
我特别困扰于理解以下代码(来自 Cocoa Programming for Mac OS X, 3rd Edition),但我也想能够独立应用这些概念而不仅仅是按照教程样例来编写代码。代码如下:
- (void)insertObject:(Person *)p inEmployeesAtIndex:(int)index
{
NSLog(@"adding %@ to %@", p, employees);
// Add inverse of this operation to undo stack
NSUndoManager *undo = [self undoManager];
[[undo prepareWithInvocationTarget:self] removeObjectFromEmployeesAtIndex:index];
if (![undo isUndoing])
[undo setActionName:@"Insert Person"];
// Finally, add person to the array
[employees insertObject:p atIndex:index];
}
- (void)removeObjectFromEmployeesAtIndex:(int)index
{
Person *p = [employees objectAtIndex:index];
NSLog(@"removing %@ from %@", p, employees);
// Add inverse of this operation to undo stack
NSUndoManager *undo = [self undoManager];
[[undo prepareWithInvocationTarget:self] insertObject:p
inEmployeesAtIndex:index];
if (![undo isUndoing])
[undo setActionName:@"Delete Person"];
// Finally, remove person from array
[employees removeObjectAtIndex:index];
}
我理解它的意思。(顺便说一下,employees
是一个自定义的Person
类的NSArray
。)
作为.NET开发者,我试图将不熟悉的Obj-C和Cocoa概念与大致类似的.NET概念联系起来。这是否类似于.NET的委托(delegate)概念,但没有类型限制?
从书本上来看这并不是百分之百清晰的,所以我在寻找真正的Cocoa/Obj-C专家的补充材料,目的是我能够理解简单(或相对简单)示例背后的基本概念。我真的希望能够独立地应用这些知识——直到第9章,我都没有遇到任何困难。但现在…
setArgument:atIndex:
中你需要传递对象的指针,所以参数赋值实际上应该写成[myInvocation setArgument:&myString atIndex:2]
。 - Ryan McCuaig