首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >定时器中的快速3定时器

定时器中的快速3定时器
EN

Stack Overflow用户
提问于 2017-05-05 08:52:18
回答 1查看 414关注 0票数 0

计时器中的计时器是如何工作的?

代码语言:javascript
复制
func startSequenz()
{
    for mainCell in mainTable {
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector:#selector(ViewController.run), userInfo: nil, repeats: true)
    }
}

func run ()
{
    for cell in table{
        timer2 = Timer.scheduledTimer(timeInterval: 1, target: self, selector:#selector(ViewController.run2), userInfo: nil, repeats: true)
    }
    timer!.invalidate()
}

func run2()
{
    currentSteps! += 1
    print("\(currentSteps!)")
    timer2!.invalidate()
}

执行func run2()从不停止。我的目标是延迟run2和sleep(1) freez GUI的执行。

更新:

我用了汤姆E的答案,它部分地起了作用。但是GUI只在执行结束时刷新一次。

代码语言:javascript
复制
func run ()
{
    for cell in table{

        DispatchQueue.global().asyncAfter(deadline: .now() + .seconds(2)) {
        // This code will be placed on a background queue and be executed a second later

            // i do my stuff   

            DispatchQueue.main.async {

                // Here you may update any GUI elements  
                self.currentCell = cell
                self.currentStep! += 1

                self.sectionHeaderText = "\(self.currentStep!) of \(self.totalSteps!)"
                self.tableView.reloadSections(IndexSet(integer: 0), with: .none)
            }
        }
    }
}

public override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    switch section {
      case 0  : return sectionHeaderText
      default : return nil
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-05-05 09:07:50

创建一个重复计时器似乎没有多大意义,它将在第一次调用其操作方法时立即失效。

如果您想要找到适当的方法来延迟代码的执行,请看一下中央调度。下面是一个具有非阻塞、延迟后台执行的代码示例:

代码语言:javascript
复制
DispatchQueue.global().asyncAfter(deadline: .now() + .seconds(1)) {
    // This code will be placed on a background queue and be executed a second later

    DispatchQueue.main.async {
        // Here you may update any GUI elements
    }
}

请确保您没有从后台队列中访问任何GUI元素。出于这个原因,示例展示了如何切换到主线程进行任何GUI更新。

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

https://stackoverflow.com/questions/43800532

复制
相关文章

相似问题

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