2012-05-02 35 views
0

一組簡化的方法來證明發生了什麼:的NSTimer無效 - 重複計時器

- (void)timerDidFire { 
    NSLog(@"fire"); 
} 

- (void)resetTimer:(NSTimer *)timer { 
    if (timer) [timer invalidate]; // timer = nil; here doesn't change anything 
    NSLog(@"%@", timer); 
    timer = [NSTimer ...Interval:1 ... repeats:YES]; 
} 

- (IBAction)pressButton { 
    [self resetTimer:myTimer]; 
} 

結算我做錯了什麼,但什麼?爲什麼每次印刷都會有額外的計時器?

回答

2

每次調用resetTimer:方法時,都會創建一個新的NSTimer實例。不幸的是,在完成此方法的執行後,您將失去對新實例的所有引用,因爲它已分配給本地變量。
您在該方法內創建的計時器未分配給myTimer變量。無論myTimer是什麼,它都不是新創建的計時器。

,你可以放棄所有的局部變量和簡單的使用是這樣的:

- (void)resetTimer { 
    [myTimer invalidate]; // calls to nil are legal, so no need to check before calling invalidate 
    NSLog(@"%@", myTimer); 
    myTimer = [NSTimer ...Interval:1 ... repeats:YES]; 
} 

- (IBAction)pressButton { 
    [self resetTimer]; 
} 
+0

我想這可能是類似的東西。愚蠢的錯誤。不知道爲什麼我認爲局部變量會做任何事情。 – Thromordyn