2016-05-31 102 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,..),所以没有看到我告诉它的定时器间隔或重复等。 –