如何从 NSInvocable 中获取 NSString 结果?

发布于 2024-10-20 20:47:14 字数 699 浏览 2 评论 0原文

下面的代码按预期工作:

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

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

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"

我已经搜索了高低,但无法弄清楚这一点。有什么帮助吗?谢谢!

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];
[invocation 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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

画尸师 2024-10-27 20:47:14

来自 NSIncation 类参考:

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

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

由于 @"test" 实际上是构造 NSString 的实例,因此您应该使用

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

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];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文