reflectionios8invokensinvocation

NSInvocation invoke giving bad access in iOS 8


I'm trying to run this code in iOS 8 but I'm getting a bad access error in the method called, this runs ok in iOS 7. Does anyone has a clue about this?

-(double) calcularColumna:(int ) anio :(int) mes :(NSString * ) columna {
NSInvocation * invocation = [selectores objectForKey:columna];
if(!invocation){
    NSString * metodo = [NSString stringWithFormat:@"fondo%@:anio:mes:",columna];
    SEL selector = NSSelectorFromString(metodo);
    if( ![self respondsToSelector:selector]) {
        return -1;
    }
    invocation = [NSInvocation invocationWithMethodSignature:[[self class] instanceMethodSignatureForSelector:selector]];
    invocation.selector = selector;
    invocation.target = self;

    [invocation setArgument:(__bridge void *)(self.valoresEntrada) atIndex:2];
    [selectores setObject:invocation forKey:columna];
}
double valor = 0;
[invocation setArgument:&anio atIndex:3];
[invocation setArgument:&mes atIndex:4];
[invocation invoke];
[invocation getReturnValue:&valor];
/* }else {
 valor = -1;
 }*/
return valor;

}

Thanks for your comments.


Solution

  • [invocation setArgument:(__bridge void *)(self.valoresEntrada) atIndex:2];
    

    is wrong. You need to pass a pointer to the value being passed. Something like

    // I don't know the type of self.valoresEntrada, but you can use the type directly
    typeof(self.valoresEntrada) temp = self.valoresEntrada;
    [invocation setArgument:&temp atIndex:2];
    

    Also, if you are going to store the invocation in a collection for use after the scope where it's created, you need to do [invocation retainArguments];


    p.s. [[self class] instanceMethodSignatureForSelector:selector] can be written as [self methodSignatureForSelector:selector]


    p.p.s. If the method signature is known and fixed at compile-time, you can use objc_msgSend directly, if you are brave.