ios - 无法调用 scheduledTimer

标签 ios swift cocoa-touch

我有这个非常简单的代码来触发计时器:

var timer = NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(2), target: self, selector: "timerDidFire:", userInfo: nil, repeats: true)

然而它给了我:

Cannot invoke 'scheduledTimerWithTimeInterval' with an argument list of type '(Double, target: TestVC -> () -> TestVC, selector: String, userInfo: nil, repeats: Bool)'

这没有任何意义,我的参数类型完全符合要求。

函数定义如下:

scheduledTimerWithTimeInterval(ti: NSTimeInterval, target aTarget: AnyObject, selector aSelector: Selector, userInfo: AnyObject?, repeats yesOrNo: Bool) -> NSTimer

我做错了什么?

最佳答案

在属性的初始值表达式中使用时

 class TestVC : UIViewController (

      var timer = ... some expression using `self` ...

      // ...
 }

self 不是 TestVC 的实例,而是类型的“柯里化(Currying)函数”

  TestVC -> () -> TestVC

这就是奇怪的错误消息的来源。实例本身是 此时尚未完全初始化。这类似于 ViewController.Type does not have a member named 中的问题,并且可以在此处应用相同的解决方案:

将变量声明为可选(或隐式解包可选) 并以某种方法对其进行初始化,例如在 viewDidLoad 中:

class TestVC: UIViewController {

    var timer : NSTimer?

    override func viewDidLoad() {
        super.viewDidLoad()
        timer = NSTimer.scheduledTimerWithTimeInterval( ... )
    }

    // ...
}

关于ios - 无法调用 scheduledTimer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30460343/

相关文章:

ios - Swift 2 - NSJONSerialization.JSONObjectWithData with guard statement "Cannot convert value of type Element..."

ios - 如何从 UITableView 中获取选定的行?

ios - IBOutlet 初始化中的 UIView 框架中心不正确

ios - 创建 iOS/OS X 跨平台类

ios - 通过shell脚本plist buddy从plist读取数组

ios - 如何在 iOS 中使用 objective-c 生成 XML 文档

arrays - 无法从数组获取数据

ios - 使用 Core Data 时需要本地数组吗?

ios - 包含 UIScrollView 的缩放后添加到 UIImageView 的注释不在正确的位置

iphone - 停用 UIScrollView 减速