什么是Swift的“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函数不能像我希望的那样工作.

也许这里的派遣功能不合适?

解决方法

dispatch_after是performSelect的一个很好的替代选择: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,selector: "handleIdleEvent:",repeats: false)
    timer = nextTimer
}

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

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

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...