Using NSTimer in swift playground [duplicate]

谁都会走 提交于 2019-11-29 22:07:45

问题


I'd like to know how to use an NSTimer inside a Swift Playground. This question has been asked before, but none of the answers actually answered the question.

Here's my Playground code:

import Foundation

class MyClass {

    func startTimer() {
        NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "onTimer:", userInfo: nil, repeats: true)
    }

    func onTimer(timer:NSTimer!) {
        println("Timer here")
    }
}

var anInstance = MyClass()

anInstance.startTimer()

Instantiating NSTimer with scheduledTimerWithTimeInterval creates the timer and schedules it on the current run loop.

But the method onTimer is never called. Why?


回答1:


First of all, your onTimer method have to be declared as @objc, or NSTimer cannot find that.

As for your question, it's because you haven't started the run loop.

To do that, CFRunLoopRun() is the simplest solution I think.

import Foundation

class MyClass {

    func startTimer() {
        NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "onTimer:", userInfo: nil, repeats: true)
    }

    @objc func onTimer(timer:NSTimer!) {
        println("Timer here")
    }
}

var anInstance = MyClass()

anInstance.startTimer()

CFRunLoopRun() // <-- HERE!

For the sake of completeness, as @MartinR metioned in the comment, you can also use XCPSetExecutionShouldContinueIndefinitely()

import Foundation
import XCPlayground
XCPSetExecutionShouldContinueIndefinitely()

class MyClass {

    func startTimer() {
        NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "onTimer:", userInfo: nil, repeats: true)
    }

    @objc func onTimer(timer:NSTimer!) {
        println("Timer here")
    }
}

var anInstance = MyClass()

anInstance.startTimer()

In this case the Playground runs only seconds specified in the Timeline:



来源:https://stackoverflow.com/questions/29232334/using-nstimer-in-swift-playground

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!