将参数传递给NSTimer调用的方法

时间:2010-10-25 01:10:36

标签: objective-c cocoa-touch selector nstimer

如何将参数传递给NSTimer调用的方法?我的计时器看起来像这样:

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

我希望能够将字符串传递给方法updateBusLocation。另外,我应该在哪里定义updateBusLocation方法?在我创建计时器的同一个.m文件中?

修改

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

由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:' * - [MapKitDisplayViewController updateBusLocation]:无法识别的选择器发送到实例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:编辑#2: 没关系,您的示例代码可以正常工作,感谢您的帮助。

6 个答案:

答案 0 :(得分:97)

您需要在目标中定义方法。由于您将目标设置为“self”,然后是同一对象需要实现该方法。但你可以将目标设定为你想要的任何东西。

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

希望有所帮助。

编辑:...简单示例:

设置计时器:

    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]);

}

答案 1 :(得分:23)

您可以使用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];
}

答案 2 :(得分:3)

对于 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

}

答案 3 :(得分:2)

Swift 中使用字典文字 将参数传递给 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)")
}

答案 4 :(得分:0)

这不是问题的直接答案,但是由于我在搜索时遇到了这个问题,并且我需要一些其他信息,因此可能会对某人有所帮助。我想在辅助类中调用一个函子,我需要传递UIViewController,而不是通过userinfo传递它,这将不允许我在其他地方手动调用该函数,而我创建了另一个函数,该定时器将从那里调用并调用了我感兴趣的函数。一种有效的解决方法。

Timer.scheduledTimer(timeInterval: 4, target: self, selector: #selector(self.timerFired), userInfo: nil, repeats:true);

func timerFired() {

myFunction(controller: self)

}

答案 5 :(得分:0)

对于 Swift 4.0:

您可以使用具有所需参数的函数,并使用“ scheduledTimer”块执行您需要重复的代码。

func someFunction(param1: Int, param2: String) {

    let timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
        print(param1)
        print(param2)
    }
}

完成操作时请小心调用 timer.invalidate(),以防止其连续运行。

相关问题