NSInvocation setArgument not working with simple int32_t

本文探讨了在Objective-C中使用NSInvocation调用带有int32_t参数的方法时遇到的问题。作者尝试传递一个整数但发现实际传递的值被错误地解释为NSNumber指针,导致传入的整数值被误解。文章提供了详细的代码示例,并解答了如何正确设置非对象类型的参数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I am facing an issue while using NSInvocation with arguments which are not objects. The simple integer value that I pass gets changed to something different.

Here is the method I am invoking:

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

And This is how I am calling it :

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

}

The result is what gets logged is not the simple 123456 value I pass but something like this:

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

What is it that I am doing wrong?

I am pretty new to Objective C but, I need to invoke a method at runtime over which I have no control. And it takes int64_t as the argument type.

Please can anyone help? Thanks....




答案:

1、You're passing an NSNumber* as the argument, not an int_32t. The NSNumber happens to wrap the integer, but it's not an integer.

Note that retainArguments may expect that the arguments are objects that can be retained. Its documentation does mention that C strings are copied, but it's not immediately obvious what happens to scalars like an int. You probably should avoid retainArguments and manage retaining and releasing yourself.

2、You are passing the wrong argument type. Since the method takes an argument of type int32_t, that's what you need to pass:

int32_t arg = 123456;

[inv setArgument:&arg atIndex:2]; //arguments 0 and 1 are self and _cmd respective

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值