如何从NSInvocation获取NSString结果?

时间:2011-03-07 19:30:26

标签: objective-c nsinvocation

以下代码按预期工作:

NSLog(@"%@", [NSString stringWithString:@"test"]; // Logs "test"

但是当我用NSInvocation替换它时,我得到一个完全不同的结果:

Class class = [NSString class];
SEL selector = @selector(stringWithString:);

NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:
                          [class methodSignatureForSelector:selector]];
[invocation setTarget:class];
[invocation setSelector:selector];
[invocation setArgument:@"test" atIndex:2];
[invocation invoke];

id returnValue = nil;
[invocation getReturnValue:&returnValue];
NSLog(@"%@", returnValue); // Logs "NSCFString"

我搜索过高低,但无法弄清楚这一点。有帮助吗?谢谢!

1 个答案:

答案 0 :(得分:7)

从NSInvocation类引用:

当参数值是一个对象时,将指针传递给应该从中复制对象的变量(或内存):

NSArray *anArray;    
[invocation setArgument:&anArray atIndex:3];

由于@“test”实际上构建了NSString的一个实例,你应该使用

NSString *testString = @"test";
[invocation setArgument:&testString atIndex:2];