加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

objective-c – 如何从NSInvocation获取NSString结果?

发布时间:2020-12-16 09:33:18 所属栏目:百科 来源:网络整理
导读:以下代码按预期工作: NSLog(@"%@",[NSString stringWithString:@"test"]; // Logs "test" 但是当我用NSInvocation替换它时,我得到一个完全不同的结果: Class class = [NSString class];SEL selector = @selector(stringWithString:);NSInvocation *invocat
以下代码按预期工作:

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];

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读