2016-07-25 69 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

相關問題