2010-10-25 15 views
55

¿Cómo puedo pasar un parámetro al método llamado por un NSTimer? Mi cronómetro se ve así:Pasar los parámetros al método llamado por un NSTimer

[NSTimer scheduledTimerWithTimeInterval:4 target:self selector:@selector(updateBusLocation) userInfo:nil repeats:YES]; 

y quiero ser capaz de pasar una cadena al método updateBusLocation. Además, ¿dónde se supone que debo definir el método updateBusLocation? ¿En el mismo archivo .m que creo el temporizador?

EDIT:

En realidad sigo teniendo problemas. Estoy recibiendo el mensaje de error:

Terminación de aplicación debido a excepción no detectada 'NSInvalidArgumentException', razón: '* - [MapKitDisplayViewController updateBusLocation]: Selector no reconocido enviado a la instancia 0x4623600'

Aquí está mi código:

- (IBAction) showBus { 

//do something 

[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateBusLocation) userInfo:txtFieldData repeats:YES]; 
[txtFieldData release]; 
} 


- (void) updateBusLocation:(NSTimer*)theTimer 
{ 
     NSLog(@"timer method was called"); 
     NSString *txtFieldData = [[NSString alloc] initWithString:(NSString*)[theTimer userInfo]]; 
if(txtFieldData == busNum.text) { 
    //do something else 
    } 
    } 

EDIT # 2: No importa que su código de ejemplo funcione bien gracias por la ayuda.

+0

pregunta sólido que estoy seguro que un montón de personas se han preguntado en un momento u otro. ¡Gracias! –

Respuesta

95

Debe definir el método en el destino. Dado que establece el objetivo como "uno mismo", entonces sí, ese mismo objeto necesita implementar el método. Pero podrías haber establecido el objetivo a cualquier otra cosa que quisieras.

userInfo es un puntero que puede establecer en cualquier objeto (o colección) que desee y que se pasará al selector de destino cuando se dispare el temporizador.

Espero que ayude.

EDITAR: ...Ejemplo simple:

Configure el temporizador:

NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:2.0 
           target:self 
           selector:@selector(handleTimer:) 
           userInfo:@"someString" repeats:NO]; 

e implementar el manejador de la misma clase (suponiendo que está configurando el objetivo de 'auto'):

- (void)handleTimer:(NSTimer*)theTimer { 

    NSLog (@"Got the string: %@", (NSString*)[theTimer userInfo]); 

} 
+0

Todavía estoy perdido, ¿te importaría darme un ejemplo de un temporizador que llama a un método y pasa un parámetro a ese método? – bubster

+0

Claro, edité mi respuesta con un simple ejemplo –

22

Usted puede pasar sus argumentos con userInfo: [NSDictionary dictionaryWithObjectsAndKeys:parameterObj1, @"keyOfParameter1"];

Un simple ejemplo:

[NSTimer scheduledTimerWithTimeInterval:3.0 
           target:self 
           selector:@selector(handleTimer:) 
           userInfo:@{@"parameter1": @9} 
           repeats:NO]; 

- (void)handleTimer:(NSTimer *)timer { 
    NSInteger parameter1 = [[[timer userInfo] objectForKey:@"parameter1"] integerValue]; 
} 
1

Para Swift haces de esta manera,

Por ejemplo, usted quiere enviar UILabel con NSTimer

override func viewDidLoad() { 
    super.viewDidLoad() 

    var MyLabel = UILabel() 
    NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: Selector("callMethod:"), userInfo: MyLabel, repeats: false) 
} 


func callMethod(timer:NSTimer){ 

    var MyLabel:UILabel = timer.userInfo as UILabel 

} 
2

ejemplo adicional en Swift usando Diccionario literal para pasando los parámetros al método llamado por NSTimer:

override func viewDidLoad() { 
    super.viewDidLoad() 

    let dictionary: [String : AnyObject] = ["first element" : "Jordan", 
              "second element" : Int(23)] 

    NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(0.41), 
              target: self, 
              selector: "foo:", 
              userInfo: dictionary, 
              repeats: false) 
} 

func foo(timer: NSTimer) { 
     let dictionary: [String : AnyObject] = timer.userInfo! as! [String : AnyObject] 
     let firstElement: String = dictionary["first element"] as! String 
     let secondElement: Int = dictionary["second element"] as! Int 
     print("\(firstElement) - \(secondElement)") 
} 
Cuestiones relacionadas