2017-05-05 94 views
0

計時器在計時器中是如何工作的?Swift 3計時器在計時器

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。

UPDATE:

從來就使用湯姆Ë答案,它部分的工作。但是GUI在執行結束時只刷新一次。

​​
+0

基本上它可以工作,但是你對**許多**單元使用**一個**(同一個)定時器,這是行不通的。 – vadian

+0

好吧我看到每個循環都會創建一個新實例。我該如何解決它?我現在無法獲得解決方案。 – ZombieIK

回答

1

創建一個重複定時器似乎沒有什麼意義,它會在第一次調用它的動作方法時立即失效。

如果您尋求正確的方法來延遲執行代碼,請查看Grand Central Dispatch。下面是與非阻塞代碼樣本,延遲後臺執行:

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更新的主線程。