2016-07-25 72 views
1

我试图设置一个定时器来定期运行一个事件,如here所述。我得到了包括hashtag参数已被弃用,所以我试图重写相应的startTimer所代码:“对成员的模糊引用'scheduledTimerWithTimeInterval(_:invocation:repeats :)'”

func startTimer() 
{ 
    let theInterval: NSTimeInterval = 5.0 

    self.timer = NSTimer.scheduledTimerWithTimeInterval 
    (
     interval: theInterval, 
     target: self, 
     selector: Selector("timerTick:"), 
     userInfo: "Hello!", 
     repeats: true 
    ) 
} 

问题是,我不断收到错误:“不明确的参考成员“scheduledTimerWithTimeInterval(_:调用:重复: )“”。但我没有试图运行scheduledTimerWithTimeInterval(_:invocation:repeats :),我试图运行scheduledTimerWithInterval:target:selector:userInfo:repeats。我认为这将从我传递的参数中显而易见。

我需要做什么改变?

+2

您不使用interval参数名称,这可能会让编译器感到困惑 – Knight0fDragon

回答

3

有两个问题:

  1. 它由scheduledTimerWithTimeInterval和开放括号之间的换行和空白混淆。

  2. 您不应该提供第一个参数标签。

所以,你可以这样做:

timer = NSTimer.scheduledTimerWithTimeInterval(
    2.0, 
    target: self, 
    selector: #selector(timerTick(_:)), 
    userInfo: "Hello!", 
    repeats: true 
) 

注意,我还与#selector语法替换Selector("timerTick:")

+0

如果选择器引用同一个类中的方法,那么也可以省略类名:'#selector(timerTick(_ :))'' –

+0

谢谢,马丁。更新了答案。 – Rob

相关问题