2017-05-26 36 views
0

我只是想知道什麼是最好的實施內存優化多功能多計時器在迅速。 定時器是併發並有弱參考與調度? 我試圖在一個視圖控制器中實現兩個定時器,並且出現錯誤。如何在swift中實現優化多重定時器?

我的計時器之一是這樣的:

func startOnPlayingTimer() { 

let queue = DispatchQueue(label: "com.app.timer") 
onPlayTimer = DispatchSource.makeTimerSource(queue: queue) 
onPlayTimer!.scheduleRepeating(deadline: .now(), interval: .seconds(4)) 
onPlayTimer!.setEventHandler { [weak self] in 
    print("onPlayTimer has triggered") 
} 
onPlayTimer!.resume() 
} 

另一個是:

carouselTimer = Timer.scheduledTimer(timeInterval: 3, target: self,selector: #selector(scrollCarousel), userInfo: nil, repeats: true) 
+1

我只會創建多個'Timer'實例。你遇到了什麼錯誤? – Paulw11

+0

@ Paulw11其實,我今天可以用'Timer'實現這個。但我懷疑這個函數線程安全嗎?並有一個「弱參考」?我正在尋找與Dispatch實現這一點,並使其線程安全和內存優化。 – Omnia

+0

線程安全和cicrcular強引用是計時器的單獨問題。沒有計時器方法會給你固有的線程安全。線程的安全性取決於你在由定時器調度的閉包中做什麼。定時器可以對能源使用產生影響,事實上蘋果公司特別建議不要將定時器用作同步技術; https://developer.apple.com/library/content/documentation/Performance/Conceptual/EnergyGuide-iOS/MinimizeTimerUse.html。您仍然沒有解釋當您嘗試使用兩個定時器時出現的「錯誤」錯誤 – Paulw11

回答

0

我不認爲有必要爲任何應用程序的多個計時器。 如果來自以前知道要觸發哪種方法,請爲每個需要觸發的方法保留布爾值,並保存方法的出現。您可以調用一次定時器,並使用一種方法來檢查所需的布爾值及其各自的方法。

的僞代碼引用了上面的邏輯是以下:

class ViewController: UIViewController { 


var myTimer : Timer! 

var methodOneBool : Bool! 
var methodTwoBool : Bool! 
var mainTimerOn : Bool! 


var mainTimerLoop : Int! 
var methodOneInvocation : Int! 
var methodTwoInvocation : Int! 

override func viewDidLoad() { 
    super.viewDidLoad() 
    configure() 
} 

func configure(){ 
    methodOneBool = false 
    methodTwoBool = false 

    methodOneInvocation = 5 // every 5 seconds 
    methodTwoInvocation = 3 //every 3 seconds 

    mainTimerOn = true // for disable and enable timer 
    mainTimerLoop = 0 // count for timer main 
} 

func invokeTimer(){ 
    myTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(checkTimerMethod), userInfo: nil, repeats: true) 
} 


func checkTimerMethod(){ 

    if(mainTimerOn){ 

     if(mainTimerLoop % methodOneInvocation == 0 && methodOneBool){ 
      // perform first method 
      // will only get inside this when 
      // methodOneBool = true and every methodOneInvocation seconds 
     } 

     if(mainTimerLoop % methodTwoInvocation == 0 && methodTwoBool){ 
      // perform second method 
      // will only get inside this when 
      // methodTwoBool = true and every methodTwoInvocation seconds 
     } 

     mainTimerLoop = mainTimerLoop + 1 

    } 
} 

} 

我希望這清除了問題,另外,如果我不明白您的要求,請評論下面,這樣我就可以相應地編輯答案

+1

國際海事組織它是簡單得多,只是有兩個計時器 – Paulw11

+0

計時器是非常沉重的對象,並需要大量的內存來調用AFAIK,所以它儘量少維護 –

+0

。一旦確定存在問題,請始終選擇最簡單的解決方案並在必要時進行優化。你的解決方案有更多的「移動部件」,因此有潛在的錯誤 – Paulw11