你在正確的軌道上爲止。
與你已有的代碼堅持,這裏是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
而且,如果你可以使用綁定的,你可以簡單地綁定文本字段的intValue
到Controller
的counter
財產。這將允許您在類接口中排除IBOutlet
,並且setIntegerValue:
行在advanceTimer
。
更新:刪除了將定時器添加到運行循環兩次的代碼。感謝Nikolai Ruhe和nschmidt注意到這個錯誤。按照nschmidt,使用setIntegerValue
方法來簡化代碼。
編輯:在錯字(無效)advanceTimer的定義:(*的NSTimer)定時器......造成惱人的「無法識別的選擇發送到實例」例外
將countdownTimer添加到運行循環兩次,這是錯誤的。 – 2009-06-23 14:32:18