2010-11-22 122 views
0

我該如何在runTime中停止NSTimer?NSTimer在運行時停止?

我使用下面的代碼。但的NSTimer運行一遍又一遍(我要重複的NSTimer,我希望停止運行時)

- (void)TimerCallback 
    { 

    ..... 
    [self.tim invalidate]; 
     self.tim = nil; 

} 


-(void)timerStart 
{ 


    self.tim = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(TimerCallback) userInfo:nil repeats:YES]; 

} 
+0

我猜你正在做的正確,不知道爲什麼NSTimer不會停止後無效消息..是'蒂姆'設置保留?或複製?同時宣佈財產 – Sanniv 2010-11-22 07:50:11

+0

我已設置爲保留在propery ..我必須分配副本? – 2010-11-22 07:50:56

回答

2
  1. 這是重複:NO。如果你希望它只能運行一次。你有重複:是的。

  2. 這是[添無效]和 self.tim無效

  3. 做self.tim =零,因爲那是釋放它。無效一切。

  4. 請注意,請確保您的財產是正確的,即
    @property(nonatomic,retain)NSTimer * happyTimer;
    and
    @synthesize happyTimer;

  5. 爲了記錄,你必須在同一個線程。

希望它有幫助。

下面是代碼切斷從工作例如生產的所有行:

NSTimer *ttt; 
@property (nonatomic, retain) NSTimer *ttt; 
@synthesize ttt; 
self.ttt = [NSTimer scheduledTimerWithTimeInterval:7.00 
    target:self selector:@selector(ringBell) userInfo:nil repeats:YES]; 
if ([ttt isValid]) 
    [ttt invalidate]; 
[ttt release]; // in dealloc 

您需要添加一些調試線的NSLog(@「我只是無效」);等等,以確保你沒有一些基本的錯誤。

+0

嗨,我想重複:是的...我按照你說的指示,但定時器仍在運行... – 2010-11-22 08:18:19

+0

關於第2點;兩者都是一樣的。 關於第3點; self.tim將定時器分配給nil。如果它(保留)釋放內存,如果它(分配)它已經釋放。在這兩種情況下都可以。 – seppo0010 2011-01-28 12:40:04

0

您的代碼似乎正確。通常這個問題是啓動計時器的兩倍。你可以試試



-(void)timerStart { 
    [self.tim invalidate]; 
    self.tim = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(TimerCallback) userInfo:nil repeats:YES]; 

}