2009-06-23 186 views
13

我試圖創建一個倒計時器是採用倒計時,一個IBOutlet連接到一個文本框,從60秒下降到0。我不知道倒數計時器

A.如何的重複限制到60和

B.如何遞減advanceTimer倒計時:

- (IBAction)startCountdown:(id)sender 
{ 
    NSTimer *countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self  selector:@selector(advanceTimer:) userInfo:nil repeats:YES]; 
    NSRunLoop *runLoop = [NSRunLoop currentRunLoop]; 
    [runLoop addTimer:countdownTimer forMode:NSDefaultRunLoopMode]; 
} 

- (void)advanceTimer:(NSTimer *)timer 
{ 
    [countdown setIntegerValue:59]; 
} 

回答

19

你在正確的軌道上爲止。

與你已有的代碼堅持,這裏是advanceTimer方法應該如何看待,使其工作:

- (void)advanceTimer:(NSTimer *)timer 
{ 
    [countdown setIntegerValue:([countdown integerValue] - 1)]; 
    if ([countdown integerValue] == 0) 
    { 
     // code to stop the timer 
    } 
} 

編輯: 爲了使整個事情更面向對象,並避免轉換從後每一次串數字和,我反而做這樣的事情:

// Controller.h: 
@interface Controller 
{ 
    int counter; 
    IBOutlet NSTextField * countdownField; 
} 
@property (assign) int counter; 
- (IBAction)startCountdown:(id)sender; 
@end 

// Controller.m: 
@implementation Controller 

- (IBAction)startCountdown:(id)sender 
{ 
    counter = 60; 

    NSTimer *countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1 
             target:self 
             selector:@selector(advanceTimer:) 
             userInfo:nil 
             repeats:YES]; 
} 

- (void)advanceTimer:(NSTimer *)timer 
{ 
    [self setCounter:(counter -1)]; 
    [countdownField setIntegerValue:counter]; 
    if (counter <= 0) { [timer invalidate]; } 
} 

@end 

而且,如果你可以使用綁定的,你可以簡單地綁定文本字段的intValueControllercounter財產。這將允許您在類接口中排除IBOutlet,並且setIntegerValue:行在advanceTimer

更新:刪除了將定時器添加到運行循環兩次的代碼。感謝Nikolai Ruhe和nschmidt注意到這個錯誤。按照nschmidt,使用setIntegerValue方法來簡化代碼。

編輯:在錯字(無效)advanceTimer的定義:(*的NSTimer)定時器......造成惱人的「無法識別的選擇發送到實例」例外

+0

將countdownTimer添加到運行循環兩次,這是錯誤的。 – 2009-06-23 14:32:18

6

您可以添加一個實例變量int _timerValue舉行定時器值,然後執行以下操作。還要注意,您正在創建的NSTimer已經在當前運行循環中進行了調度。

- (IBAction)startCountdown:(id)sender 
{ 
    _timerValue = 60; 
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(advanceTimer:) userInfo:nil repeats:NO]; 
} 

- (void)advanceTimer:(NSTimer *)timer 
{ 
    --_timerValue; 
    if(self.timerValue != 0) 
     [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(advanceTimer:) userInfo:nil repeats:NO]; 

    [countdown setIntegerValue:_timerValue]; 
}