如何在达到0时重置倒数计时器? (Xcode 4)

问题描述:

第一个问题,我已经研究了这一点,似乎无法找到任何答案。如何在达到0时重置倒数计时器? (Xcode 4)

我想在我的应用程序中实现一个倒数计时器,该计时器在30秒开始,并在打到0时重置。它将以1秒为间隔计数。我玩过苹果提供的资源,我似乎无法按照我刚刚解释的那样实施NStimer。有没有关于我如何编码的建议?我最终希望将其链接到一个按钮,该按钮将在按下时启动计时器。我很欣赏这个话题的任何建议!

在您的.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; 
    } 
}