Question

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....

Was it helpful?

Solution 2

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.

OTHER TIPS

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 respectively, automatically set by NSInvocation
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top