NSInvocation troubles

I’ve been working on an iPhone app and I ran into some trouble using NSInvocation while trying to invoke a function. I finally got it to work and so I thought I would share it with the world. Just a side-note, the mistake I made was quite noob.

To create the invocation:

Where t is of type (id) and s is of type (SEL).


NSMethodSignature * sig = [[t class] instanceMethodSignatureForSelector:s];
invocation = [NSInvocation invocationWithMethodSignature:sig];
[invocation setTarget:t];
[invocation setSelector:s];
[invocation retain];

Then to invoke the function:


[invocation invoke];

Here is the function I was trying to invoke:


- (void)_someFunc:(CocosNode *)node data:(void*)someData;

Now, the code NSInvocation code above is wrapped up in a class
and you have to pass in (id) t, (SEL) s and (void*)data. Then it takes
that info and it creates the invocation above. So I passed in:


[CallFuncND actionWithTarget:self selector:@selector(_someFunc) data:someData]

See the mistake? The selector I passed in was just _someFunc instead of _someFunc:data:
and so when it created in the method signature it wasn’t able to find the method and so
it returned nil, which was being passed into NSInvocation and so it seg faulted. This happened
because I’m still used to C and C++ where you a function is defined as int _funcName(param1, param2). So the fixed code is actually:


[CallFuncND actionWithTarget:self selector:@selector(_someFunc:data:) data:someData]


About this entry