什么是" cleartimeout"相当于Swift?

时间:2014-11-07 18:45:26

标签: swift timeout settimeout cleartimeout

我正在尝试在文本输入字段上设置超时,该字段仅在用户停止输入后的第二秒内实现内部代码。因此,当用户输入时,我会不断调用cleartimeout并重新启动setTimeout。

我最初在Objective C中查看performSelector函数,但看起来没有Swift等价物。

然后我转到Swift中的GCD函数,寻找执行此操作的方法。

以下是我提出的建议:

var delta: Int64 = 1 * Int64(NSEC_PER_SEC)
var time = dispatch_time(DISPATCH_TIME_NOW, delta)
dispatch_suspend(dispatch_get_main_queue())
dispatch_after(time, dispatch_get_main_queue(), {
    println("timeout")
});

dispatch_suspend函数不能像我希望的那样工作。

也许这里的调度功能不合适?

1 个答案:

答案 0 :(得分:7)

dispatch_afterperformSelect:afterDelay:的一个很好的选择但是我不认为这些都是你想要的(因为一旦你设置它们,就没有办法停止它们)。

如果您只是在闲置一秒钟之后才打算拨打一段代码,那么我认为您想要使用计时器(例如NSTimer就好了,或者您可以使用调度计时器)。最重要的是,每次进行键盘交互时,查看是否有待处理的计时器,如果是,则使其无效,然后安排新计时器。

所以我可能倾向于在S​​wift 3中执行类似下面的操作。例如,在iOS 10及更高版本中,您可以使用块再现:

weak var timer: Timer?

func resetTimer() {
    timer?.invalidate()
    timer = .scheduledTimer(withTimeInterval: 1.0, repeats: false) { [weak self] timer in
        // do whatever you want when idle after certain period of time
    }
}

或者,如果您需要支持早期没有基于块的计时器的iOS版本:

weak var timer: Timer?

func resetTimer() {
    timer?.invalidate()
    timer = .scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(handleIdleEvent(_:)), userInfo: nil, repeats: false)
}

func handleIdleEvent(_ timer: Timer) {
    // do whatever you want when idle after certain period of time
}

或者,在Swift 2中:

weak var timer: NSTimer?

func resetTimer() {
    timer?.invalidate()
    let nextTimer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "handleIdleEvent:", userInfo: nil, repeats: false)
    timer = nextTimer
}

func handleIdleEvent(timer: NSTimer) {
    // do whatever you want when idle after certain period of time
}

顺便说一下,我不确定你对dispatch_suspend的意图是什么,但不要暂停主队列。你永远不想做任何可能干扰主队列及时处理事件的事情(即永远不会阻塞/暂停主队列)。

相关问题