2010-04-16 10 views
22

Otra pregunta mía sobre optimizing Objective C programs inspiró lo siguiente: ¿Alguien tiene un pequeño ejemplo usando SEL e IMP cuando el Método tiene dos (o más) enteros para la entrada?Objective-C y uso de SEL/IMP

+1

¿Puede dar más detalles? No estoy seguro de lo que quieres decir con SEL e IMP. – drekka

+0

Sí, ¿qué quieres hacer exactamente? –

Respuesta

45

Aquí hay un good tutorial para obtener el IMP actual (con una descripción general de los IMP). Un ejemplo muy básico de PIM y SELs es:

- (void)methodWithInt:(int)firstInt andInt:(int)secondInt { NSLog(@"%d", firstInt + secondInt); } 

SEL theSelector = @selector(methodWithInt:andInt:); 
IMP theImplementation = [self methodForSelector:theSelector]; 
//note that if the method doesn't return void, you have to explicitly typecast the IMP, e.g. int(* foo)(id, SEL, int, int) = ... 

A continuación, podría invocar el IMP, así:

theImplementation(self, theSelector, 3, 5); 

Por lo general hay ninguna razón para necesitar PIM menos que esté haciendo vudú serio - se Hay algo específico que quieras hacer?

+3

@eman: necesita convertir ese retorno así: void (* theImplementation) (id, SEL, int, int) = (void (*) (id, SEL, int, int)) [self methodForSelector: theSelector]; –

+0

@Jason Coco: corrígeme si me equivoco, pero creo que IMP está tipeado como (id, SEL, ...), por lo que no debería importar (aunque no es seguro, pero si necesitas seguridad tipográfica, probablemente no deberías estar usando IMP). – shosti

+3

Tiene razón, ya que este método está vacío, está bien, pero obtendrá errores en muchas otras instancias. Tu/necesitar/lanzar fue probablemente demasiado fuerte, tu/siempre deberías lanzar/es probablemente más correcto;) - pero dada esta pregunta, creo que el OP probablemente/no debería/estaría usando IMP tampoco. –

1

Ahora que tengo este trabajo gracias a eman, puedo añadir otro ejemplo:

SEL [email protected](getRankOf:::::::);

IMP rankingMethod=[eval methodForSelector:cardSelector];

rankingMethod(eval, cardSelector, 0, 1, 2, 3, 4, 5, 6);

no necesito esto para nada útil, ¡Solo necesitaba satisfacer mi curiosidad! Gracias de nuevo.

+0

Otro buen enlace para optimizar Objective-C es http://www.mulle-kybernetik.com/artikel/Optimization/opti-3-imp-deluxe.html – SK9

1

Aquí hay otra posible alternativa. Esto evita el bloqueo, pero el corte no funciona.

- (void)setUp 
{ 
    [super setUp]; 

    [self [email protected](firstName) toClass:[User class]]; 
    [self [email protected](lastName) toClass:[User class]]; 
} 

- (void)addSelector:(SEL)selector toClass:(Class)class 
{ 
    NSString *uniqueName = [NSString stringWithFormat:@"%@-%@", NSStringFromClass(class), NSStringFromSelector(selector)]; 
    SEL sel = sel_registerName([uniqueName UTF8String]); 
    IMP theImplementation = [class methodForSelector:sel]; 
    class_addMethod(class, selector, theImplementation, "[email protected]:@"); 
} 
Cuestiones relacionadas