开发者

How can I get an NSString result from an NSInvocation?

The following code works as expected:

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

But when I replace it with an NSInvocation, I get a totally different result:

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

NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:
                          [class methodSignatureForSelector:selector]];
[invocation setTarget:class];
[invocation setSelector:selector];
[invocatio开发者_开发技巧n setArgument:@"test" atIndex:2];
[invocation invoke];

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

I've searched high and low, but cannot figure this out. Any help? Thanks!


From the NSInvocation class reference:

When the argument value is an object, pass a pointer to the variable (or memory) from which the object should be copied:

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

Since @"test" is actually constructing an instance of NSString, you should use

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜