在 swift playground 中使用 NSTimer [英] Using NSTimer in swift playground

查看:93
本文介绍了在 swift playground 中使用 NSTimer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在 Swift Playground 中使用 NSTimer.​​之前有人问过这个问题,但没有一个答案真正回答了这个问题.

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.

这是我的 Playground 代码:

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()

使用 scheduledTimerWithTimeInterval 创建计时器将其安排在当前运行循环.

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

但是方法 onTimer 永远不会被调用.为什么?

But the method onTimer is never called. Why?

推荐答案

首先,你的 onTimer 方法必须声明为 @objcNSTimer 找不到.

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

至于你的问题,是因为你还没有启动run loop.

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

要做到这一点,CFRunLoopRun() 是我认为最简单的解决方案.

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!

<小时>

为了完整起见,正如@MartinR 在评论中提到的,您也可以使用 XCPSetExecutionShouldContinueInfinitely()

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:

这篇关于在 swift playground 中使用 NSTimer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆