views:

591

answers:

3

I want to invoke a selector of a method that has the usual NSError** argument:

-(int) getItemsSince:(NSDate *)when dataSelector:(SEL)getDataSelector error:(NSError**)outError  {
    NSArray *data = nil;
    if([service respondsToSelector:getDataSelector]) {
        data = [service performSelector:getDataSelector withObject:when withObject:outError];
        // etc.

... which the compiler doesn't like:

warning: passing argument 3 of 'performSelector:withObject:withObject:' from incompatible pointer type

Is there any way around this short of encapsulating the pointer in an object?

+2  A: 

I'm not positive, but you may want to take a look at using an NSInvocation instead of -performSelector:withObject:withObject. Since NSInvocation takes arguments of type void*, it may/should let you set whatever you want as an argument.

It'll require several more lines of code than a simple performSelector: call, but it'll probably be more convenient than wrapping your pointer in an object.

Matt Ball
+3  A: 

NSError** is not an object (id), which performSelector wants for each of the withObject args. You could go to NSInvocation, but that seems like a lot of work if this is just a single message you want to use. Try defining an intermediate selector method that takes as an arg your wrapped NSError** in an object, and let that method do the performSelector on it (which I think was probably what you meant at the end of your question?)

jbm
+13  A: 

Check out NSInvocation, which lets you "performSelector" in a much more flexible way.

Here's some code to get you started:

if ([service respondsToSelector:getDataSelector]) {
    NSArray *data;
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:
        [service methodSignatureForSelector:getDataSelector]];
    [invocation setTarget:delegate];
    [invocation setSelector:getDataSelector];
    // Note: Indexes 0 and 1 correspond to the implicit arguments self and _cmd, 
    // which are set using setTarget and setSelector.
    [invocation setArgument:when atIndex:2]; 
    [invocation setArgument:outError atIndex:3];
    [invocation invoke];
    [invocation getReturnValue:&data];
}
Martin Gordon
Just for correctness - [self methodSignatureForSelector:getDataSelector]] on the third line above should be [service methodSignatureForSelector:getDataSelector]]
edoloughlin
Steven Fisher