代码之家  ›  专栏  ›  技术社区  ›  Aaron Bratcher

为什么计时器不启动?

  •  3
  • Aaron Bratcher  · 技术社区  · 11 年前

    在操场上试过,但“计时器”从未打印过。为什么计时器不启动?

    class Tester {
        var myTimer:NSTimer?
    
        init() {
            print("initialized")
            myTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "timerFunc:", userInfo: nil, repeats: true)
        }
    
        func timerFunc(timer:NSTimer) {
            print("timer")
        }
    }
    
    var test = Tester()
    

    然后我尝试使用测试器子类NSObject,并得到了相同的结果。“初始化”打印,但不是“计时器”。也没有产生错误。

    class Tester:NSObject {
        var myTimer:NSTimer?
    
        override init() {
            super.init()
            print("initialized")
            myTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "timerFunc:", userInfo: nil, repeats: true)
        }
    
        func timerFunc(timer:NSTimer) {
            print("timer")
        }
    }
    
    
    var test = Tester()
    
    1 回复  |  直到 11 年前
        1
  •  1
  •   AstroCB    11 年前

    这是很奇怪的:似乎 NSTimer ,必须运行runloop,这样您才能调用它:

    let mainLoop = NSRunLoop.mainRunLoop()
    mainLoop.addTimer(test.myTimer!, forMode: NSDefaultRunLoopMode)
    

    将计时器添加到运行循环是允许它调用 timerFunc 。然而 NSRunLoop 不在Playground中运行(主循环在运行当前代码后停止),因此不能使用 NSTimer公司 像这样(你必须在项目中使用它)。