【问题标题】:How do I reset a countdown timer when it reaches 0? (Xcode 4)当倒数计时器达到 0 时,如何重置倒数计时器? (Xcode 4)
【发布时间】:2011-11-21 17:47:13
【问题描述】:
第一个问题,我对此进行了研究,似乎找不到任何答案。
我想在我的应用程序中实现一个倒计时计时器,该计时器从 30 秒开始并在它达到 0 时重置。它将以 1 秒的间隔倒计时。我已经使用了 Apple 提供的资源,但我似乎无法像我刚才解释的那样实现 NStimer。对我如何编码有什么建议吗?我最终想将此链接到一个按钮,该按钮将在按下时启动计时器。我很感激关于这个话题的任何建议!
【问题讨论】:
标签:
xcode4
timer
nstimer
countdown
【解决方案1】:
在您的 .h 中
@interface YourObject : NSObject {
int countdownNumber;
NSTimer* timer;
}
@property (nonatomic, assign) int countdownNumber;
@property (nonatomic, retain) NSTimer* timer;
- (IBAction)clickOnButton:(id)sender
- (void)countdown;
@end
在您的 .m 中
yourInitMethod { // ViewDidLoad, initWith...., or any init method you have
self.timer = nil;
}
- (IBAction)clickOnButton:(id)sender {
if (self.timer != nil) {
[self.timer invalidate];
}
self.countdownNumber = 30;
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countdown) userInfo:nil repeats:YES];
}
- (void)countdown {
self.countdownNumber--;
if (self.countdownNumber == 0) {
[self.timer invalidate];
self.timer = nil;
}
}