簡體   English   中英

如何從NSInvocation獲取NSString結果?

[英]How can I get an NSString result from an 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"

我搜索過高低,但無法弄清楚這一點。 有幫助嗎? 謝謝!

從NSInvocation類引用:

當參數值是對象時,將指針傳遞給應從中復制對象的變量(或內存):

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

因為@“test”實際上構建了NSString的一個實例,所以你應該使用

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM