How can I get the NSString result from NSInvocation?

The following code works as expected:

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

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

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"

I searched high and low, but cannot figure it out. Any help? Thank!

+3
source share
1 answer

From the NSInvocation class reference:

When the value of the argument 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" actually creates an NSString instance, you should use

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

All Articles