NSInvocation setArgument不能使用简单的int32_t

Nis*_*sha 2 integer objective-c nsinvocation

我在使用NSInvocation时使用非对象的参数时遇到问题.我传递的简单整数值变为不同的东西.

这是我调用的方法:

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

这就是我所说的:

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

}
Run Code Online (Sandbox Code Playgroud)

结果是记录的不是我传递的简单123456值,但是这样的事情:

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

我做错了什么?

我对Objective C很新,但是,我需要在运行时调用一个我无法控制的方法.它需要int64_t作为参数类型.

请任何人可以帮忙吗?谢谢....

rma*_*ddy 6

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

int32_t arg = 123456;

[inv setArgument:&arg atIndex:2]; //arguments 0 and 1 are self and _cmd respectively, automatically set by NSInvocation
Run Code Online (Sandbox Code Playgroud)