3

I'm using NSInvocation to call a method, which I don't know at compile time.

It works fine, by I didn't find how to pass an argument of type NSError**.

Just as an example, suppose I want to call the method -(BOOL)removeItemAtPath:(NSString *)path error:(NSError **)error from NSFileManager.

The code would look something like this:

NSFileManager *manager = [NSFileManager defaultManager];
SEL selector = @selector(removeItemAtPath:error:);
NSMethodSignature *signature = [manager methodSignatureForSelector:selector];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
[invocation setTarget:manager];
[invocation retainArguments];
[invocation setSelector:selector];

NSString *path = ...;
[invocation setArgument:&path atIndex:2];
NSError *error = ...;
[invocation setArgument:&error atIndex:3];    // Passing NSError*, not NSError**

This is a simplified example. I avoided adding the error-checking code to make it easier to read.

Also, I don't know the type of the arguments at compile time, I just get the parameters as id.

This is what I tried, but didn't work

id argument = ...
NSUInteger index = ...
const char *argType = [signature getArgumentTypeAtIndex:index];
if (strcmp(argType, "^@") == 0) {
    // object pointer
    id __strong *argumentPointer = &argument;
    [invocation setArgument:&argumentPointer atIndex:index];
}
else {
    [invocation setArgument:&argument atIndex:index];
}
3
  • To be honest, I'd try a different approach. There is very little chance that you can get an NSError* __autoreleasing* parameter handled correctly.
    – gnasher729
    Sep 24, 2014 at 15:33
  • @gnasher729, what would you recommend? Sep 24, 2014 at 16:12
  • I'd probably try to use a block, or a switch statement handling multiple functions etc.
    – gnasher729
    Sep 25, 2014 at 13:37

1 Answer 1

0

Found it!

The by reference parameter needed to be declared as __autoreleasing

This is the code that is working now:

id __autoreleasing argument = ...
NSUInteger index = ...
const char *argType = [signature getArgumentTypeAtIndex:index];
if (strcmp(argType, "^@") == 0) {
    // object pointer
    NSObject * __autoreleasing *argumentPointer = &argument;
    [invocation setArgument:&argumentPointer atIndex:index];
}
else {
    [invocation setArgument:&argument atIndex:index];
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.