Eche un vistazo a la documentación de NSObject
. En este caso:
[parent performSelector:sel withObject:[NSNumber numberWithInt:i]];
(tenga en cuenta que este método es en realidad aparece en la documentación NSObject
protocol). Desde -[NSObject performSelector:withObject:]
requiere un argumento objeto, tendrá que escribir un envoltorio en la clase de padres como
-(void)myMethodForNumber:(NSNumber*)number {
[self myMethod:[number intValue]];
}
a desempacar el NSNumber
.
Si realmente desea invocar un método que toma argumentos que no sean objeto directamente (por ejemplo, usted no tiene control de la fuente y destinatario de la llamada no desea agregar una categoría), puede utilizar NSInvocation
:
NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[parent methodSignatureForSelector:sel]];
[inv setSelector:sel];
[inv setTarget:parent];
[inv setArgument:&i atIndex:2]; //arguments 0 and 1 are self and _cmd respectively, automatically set by NSInvocation
[inv invoke];
en una nota, el método se parece a un método init
, pero no sigue el patrón de inicialización correcta para Objective-C. Debe llamar al inicializador de superclases y debe probar el resultado de nil
de esa llamada y debe regresar por su cuenta desde el método de inicialización. En todos los casos, sus métodos de inicializador de Objective-C debe ser similar:
-(id)myInitMethod {
self = [super init];
if(self != nil) {
//perform initialization of self
}
return self;
}
Su método (si se trata de un método init) tendría el siguiente aspecto:
-(id) init: (SEL)sel owner:(NSObject*) parent
{
self = [super init];
if(self != nil) {
int i = 10;
NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[parent methodSignatureForSelector:sel]];
[inv setSelector:sel];
[inv setTarget:parent];
[inv setArgument:&i atIndex:2]; //arguments 0 and 1 are self and _cmd respectively, automatically set by NSInvocation
[inv invoke];
}
return self;
}
Para ser más Objective-C estilísticamente, Cambiaría el nombre del inicializador -(id)initWithSelector:owner:
también.
gracias, esto va más allá. Supuse que podría necesitar usar NSInvocation pero no estaba seguro. Gran respuesta. – madmik3
Como comentario adicional, incluso si no tiene control sobre el destinatario, aún podría escribir un método de contenedor utilizando una categoría en esa clase para desempaquetar el objeto en el tipo primitivo. –
Buen punto, Ed. –