2011-05-03 60 views
0

我的代碼如下:的NSTimer火災問題(而不是常見的無效問題)

- (void) restart { 
    [ self pause ]; 
    //init something here... 
    [ self proceed ]; 
} 

- (void) pause { 
    if ([ _timer isValid ]) { 
     [ _timer invalidate ]; 
     _timer = nil; 
    } 
} 

- (void) proceed { 
    _timer = [ NSTimer scheduledTimerWithTimeInterval: 0.1 target: self selector: @selector (fireHandler) userInfo: nil repeats: YES ]; 
} 

主要是它工作正常,但我發現,在某些情況下,當我調用的方法「重啓」超過一次,有時候,fireHandler已經一個一個時間間隔內調用一個以上的時間(或一個時間間隔是越來越短,無論如何,它的運行速度更快突然)。

現在我的發件人添加到fireHandler,並且使用的NSLog檢查內存地址,我找到了如下的內容:

< _ NSCFTimer:0x4e610a0> < _NSCFTimer:0x4e610a0> < _ NSCFTimer:0x4e610a0> < _NSCFTimer:0x4e610a0> < _ NSCFTimer:0x4e610a0> < _NSCFTimer:0x4e610a0>

,重複......這意味着,它始終是相同的定時器。 但有時當我打電話 「重啓」 了,表示

< _ NSCFTimer:0x4e3d740> < _NSCFTimer:0x4e610a0> < _ NSCFTimer:0x4e3d740> < _NSCFTimer:0x4e610a0> < _ NSCFTimer:0x4e3d740> < _NSCFTimer:0x4e610a0> ...重複

這意味着有兩個t imer,似乎第一個並沒有按時無效和釋放。它與第二個同時運行,幾秒鐘後,第二個被移除後,即使第一個仍然活着!

它將一段時間後再次出現。這種情況並不常見,如果沒有規則,就會發生在整個時間的大約30%。我對此沒有任何想法....如果有人能給我一些想法,至少得到確切的問題。

+0

確保您每次都從同一個線程調用'restart'。 – 2011-05-03 12:01:05

回答

1

[NSTimer scheduledTimerWithTimeInterval]創建和調度各調用它一個新的計時器。所以,當你調用proceed幾次,系統會創建每次啓動一個新的計時器,覆蓋你的_timer參考,並創造泄漏。

我不能說爲什麼你描述的行爲,卻意外地調用proceed幾次可能是原因。請考慮重寫它,而不是看看是否有幫助:

- (void)proceed 
{ 
    [_timer invalidate]; 
    _timer = [NSTimer schedule...]; 
} 
+0

謝謝您的回覆,在這種情況下,我從不直接調用「繼續」,而是每次調用「重新啓動」。所以,它已經用方法「暫停」來處理無效。現在,我將發件人添加到fireHandler,並且使用的NSLog檢查內存地址,我發現了一些如下: – 2011-05-03 10:27:28

+0

<__ NSCFTimer:0x4e610a0> <__ NSCFTimer:0x4e610a0> <__ NSCFTimer:0x4e610a0> <__ NSCFTimer:0x4e610a0> < __NSCFTimer:0x4e610a0> <__ NSCFTimer:0x4e610a0> 並重復...這意味着它始終是同一個計時器。 – 2011-05-03 10:28:46

+0

但是當我打電話 「重啓」 了,<__ NSCFTimer:0x4e3d740>有時 <__ NSCFTimer:0x4e610a0> <__ NSCFTimer:0x4e3d740> <__ NSCFTimer:0x4e610a0> <__ NSCFTimer:0x4e3d740> <__ NSCFTimer:0x4e610a0> ...它意味着有兩個計時器,看起來第一個計時器並沒有失效並準時釋放。並在同一時間與第二個一起運行,過了一段時間,它消失... – 2011-05-03 10:32:14