2016-05-31 105 views
0

我想從NSTimer調用一個函數myTestFunction(day),天是一個int。Swift NSTimer傳遞變量語法

NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: #selector(ViewController.myTestFunction(_:)), userInfo: day, repeats: true) 

Xcode的編譯器,促使我對上述語法,但是當我把測試的FUNC它似乎​​並沒有被調用。有任何想法嗎?

回答

0

參數selector中指定的方法只接受一個必須是NSTimer類型的參數。該文檔說:計時器將自身作爲參數

func myTestFunction(timer : NSTimer) { 

其他(除了沒有參數)不起作用。

但是你可以通過userInfo讓您通過整數例如

let day = timer.userInfo as! Int 
+0

我以爲用戶信息的主意:選擇是讓你變(S)/字典傳遞給通過的NSTimer啓動的功能? –

+0

是的,這是正確的方法,但不是像'testFunction(day)'這樣的直接參數。用'timer.userInfo'獲取userInfo對象。我更新了答案。 – vadian

+0

對不起,我很厚,你的建議似乎失去了典型的NSTimer構造(例如NSTimer.scheduledTimerWithTimeInterval(0.1,..),所以沒有看到我告訴它的定時器間隔或重複等。 –