天天看點

使用線程安全的 MSWeakTimer ,它不會對目标進行retain操作,避免循環引用MSWeakTimer

使用線程安全的 MSWeakTimer ,它不會對目标進行retain操作,避免循環引用MSWeakTimer

簡易翻譯:該timer沒有runloop概念,線程安全,沒有循環引用現象。

thread-safe <code>nstimer</code> drop-in alternative that doesn't retain the target and supports being used with <code>gcd</code>queues.

這是個線程安全的 nstimer,他不會對目标進行retain操作,而且,他還支援gcdqueues。

the first motivation for this class was to have a type of timer that objects could own and retain, without this creating a retain cycle ( like <code>nstimer</code> causes, since it retains its target ). this way you can just release the timer in the <code>-dealloc</code> method of the object class that owns the timer.

寫這個類的動機是,我想使用這樣的nstimer,他不會對object進行retain操作,而且,更不會出現循環引用(系統的nstimer就會出現這個問題)。然後呢,你可以在-dealloc方法中來釋放這個timer。

the other problem when using <code>nstimer</code> is this note on the documentation:

另一個使用nstimer會出現的問題在以下文檔中提出了:

special considerations you must send this message from the thread on which the timer was installed. if you send this message from another thread, the input source associated with the timer may not be removed from its run loop, which could prevent the thread from exiting properly. 需要特别注意的地方 你必須在目前的線程中給你建立的nstimer發送資訊,如果你是從另外一個線程中發過來的資訊,那麼,這個timer可能就不會從他目前的run loop中移除,那個會很出現問題的。

more often than not, an object needs to create a timer and invalidate it when a certain event occurs. however, doing this when that object works with a private <code>gcd</code> queue gets tricky. this timer object is thread safe and doesn't have the notion of run loop, so it can be used with <code>gcd</code> queues and installed / invalidated from any thread or queue.

不管怎樣,一個對象建立出一個定時器,當觸發了幾次事件後,就銷毀這個定時器。然而,你如果在gcd隊列中來銷毀這個定時器,效果非常微妙(有可能出現記憶體洩露)。而大哥我寫的這個定時器是線程安全的,他不存在run loop的概念,是以,他可以在任何的gcdqueue中進行初始化以及移除掉。

the implementation of <code>msweaktimer</code> was reviewed and validated by a <code>libdispatch</code> (<code>gcd</code>) engineer at the wwdc 2013 core os lab.

create an <code>msweaktimer</code> object with this class method:

繼續閱讀