将parameter passing给由NSTimer调用的方法

我怎样才能传递一个参数到NSTimer调用的方法? 我的计时器看起来像这样:

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

我想能够传递一个string的方法updateBusLocation。 另外,我应该在哪里定义方法updateBusLocation? 在创build计时器的同一个.m文件中?

编辑:

其实我还有问题 我收到错误消息:

终止应用程序由于未捕获的exception“NSInvalidArgumentException”,原因:' * – [MapKitDisplayViewController updateBusLocation]:无法识别的select器发送到实例0x4623600'

这是我的代码:

 - (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 } } 

编辑#2:没关系您的示例代码工作正常感谢您的帮助。

您需要在目标中定义方法。 既然你把目标设置为“自我”,那么是的,同一个对象需要实现该方法。 但是你可以把目标设定为你想要的任何东西。

userInfo是一个指针,您可以将其设置为您喜欢的任何对象(或集合),并在计时器激发时传递给目标select器。

希望有所帮助。

编辑:…简单的例子:

设置定时器:

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

并在相同的类中实现处理程序(假设您将目标设置为“self”):

 - (void)handleTimer:(NSTimer*)theTimer { NSLog (@"Got the string: %@", (NSString*)[theTimer userInfo]); } 

你可以传递你的参数userInfo: [NSDictionary dictionaryWithObjectsAndKeys:parameterObj1, @"keyOfParameter1"];

一个简单的例子:

 [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]; } 

Swift中使用Dictionary literal 将parameter passingNSTimer调用的方法的附加示例:

 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)") } 

对于Swift来说,

例如,你想发送与NSTimer的 UILabel

 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 }