首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Swift中与定时器同步for循环

在Swift中与定时器同步for循环
EN

Stack Overflow用户
提问于 2015-02-10 00:14:32
回答 1查看 1K关注 0票数 0

对于我正在处理的应用程序的一部分,涉及存储在对象数组中的一系列定时器。理想情况下,我想迭代这个数组,获取计时器的持续时间,然后继续倒计时。计时器完成后,转到数组中的下一项,并重复该过程。

代码语言:javascript
复制
for(index, content) in enumerate timerList{
    doneTimer = NSTimer.scheduledTimerWithTimeInterval(timerList[index].duration, target: self, selector: Selector("finished:"), userInfo: nil, repeats: false)
}

func finished(timer : NSTimer){
     //do whatever and tell the loop to get the next item?
}

在进入数组中的下一个项目之前,在计时器结束之前,什么是最好的方法来让这个for循环“暂停”?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-02-10 01:01:18

在任何类型的GUI应用程序中,基本规则之一是不想“暂停”、“停止”或“等待”。相反,您想要做的是启动一个稍后将完成的操作,返回到GUI,然后当该操作完成时,选择您停止的地方。

在你的问题中,你想要做的似乎是找到最近的计时器,启动它,在GUI中显示一些东西,然后在计时器启动之前什么也不做。

考虑到这一点,您想要采取的基本模型是找到最早的定时器,启动它,在GUI中显示某些内容,然后返回到系统。当计时器启动时,您可以重复这个过程。

在你最初的问题中有很多含糊不清的地方,你最终会遇到这样的情况:

代码语言:javascript
复制
class TimerController {
    var timers = [Timer]()
    var runningTimer : NSTimer?
    var countDownDisplay : UILabel?

    class Timer {
        let fireDate : NSDate

        init(fireDate:NSDate) {
            self.fireDate = fireDate
        }
    }

    // given an array of NSTimer, find the earliest one to fire
    func findEarliestTimer() -> Timer? {
        return timers.sorted( { return $0.fireDate.timeIntervalSince1970 < $1.fireDate.timeIntervalSince1970 } ).first
    }

    func scheduleEarliestTimer() {
        runningTimer?.invalidate()
        runningTimer = nil

        if let timer = findEarliestTimer() {
            let duration = min(1.0, timer.fireDate.timeIntervalSinceNow)
            runningTimer = NSTimer.scheduledTimerWithTimeInterval(duration, target: self, selector: "finish", userInfo: timer, repeats: false)
        }
    }

    func finish(nstimer:NSTimer) {
        let timer = nstimer.userInfo as Timer

        // update the gui countdown
        self.countDownDisplay?.text = "\(floor(timer.fireDate.timeIntervalSinceNow))"

        // remove timer
        timers = timers.filter { $0 !== timer }

        // schedule the next timer
        self.scheduleEarliestTimer()
    }
}

请注意,当计时器停止时,我使用NSDate来保持,而不是持续时间,因为只有在知道起始点时,“持续时间”才有意义。如果要连续触发具有固定持续时间的操作字符串,请酌情修改。

因为您想要显示某种倒计时,所以您需要修改NSTimer,使其每秒钟触发一次,直到适当的时间,每次它启动时都更新倒计时。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28421929

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档