gpt4 book ai didi

objective-c - NSInvocation setArgument 不适用于简单的 int32_t

转载 作者:行者123 更新时间:2023-12-04 16:05:43 25 4
gpt4 key购买 nike

我在将 NSInvocation 与不是对象的参数一起使用时遇到问题。我传递的简单整数值已更改为不同的值。

这是我正在调用的方法:

+(NSString*) TestMethod2 :(int32_t) number
{
NSLog(@"*************** %d ******************", number);
return @"success";
}

我就是这样调用它的:

-(void) TestInvocationUsingReflection
{
id testClass = NSClassFromString(@"TestClass");
NSMethodSignature * methodSignature = [testClass methodSignatureForSelector:@selector(TestMethod2:)];

NSInvocation *inv = [NSInvocation invocationWithMethodSignature:methodSignature];
[inv setSelector:@selector(TestMethod2:)];
[inv setTarget:testClass];
NSNumber * arg = [NSNumber numberWithInt:123456];

[inv setArgument:&arg atIndex:2]; //arguments 0 and 1 are self and _cmd respectively, automatically set by NSInvocation
[inv retainArguments];
NSUInteger length = [[inv methodSignature] methodReturnLength];
id result = (void *)malloc(length);

[inv invoke];
[inv getReturnValue:&result];

}

结果是记录的不是我传递的简单 123456 值,而是类似这样的值:

****** 180774176 *********

我做错了什么?

我是 Objective C 的新手,但我需要在运行时调用一个我无法控制的方法。并且它以 int64_t 作为参数类型。

请问有人能帮忙吗?谢谢....

最佳答案

您传递了错误的参数类型。由于该方法采用 int32_t 类型的参数,因此您需要传递的是:

int32_t arg = 123456;

[inv setArgument:&arg atIndex:2]; //arguments 0 and 1 are self and _cmd respectively, automatically set by NSInvocation

关于objective-c - NSInvocation setArgument 不适用于简单的 int32_t,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14985440/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com