将停止和重置按钮添加到NSTimer

时间:2013-11-04 00:06:08

标签: objective-c nstimer reset

我创建了一个只需几分钟的NSTimer,我希望为它添加一个停止和重置按钮。到目前为止,我的代码看起来像这样:

@implementation TimeController

int timeTick = 0;


NSTimer *timer;   

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    labelTime.text = @"0";
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)startTimer:(id)sender {
    [timer invalidate];
    timer= [NSTimer scheduledTimerWithTimeInterval:60.0 target:(self) selector:(@selector(tick)) userInfo:(nil) repeats:(YES)];
}

-(void)tick{
    timeTick++;
    NSString *timeString = [[NSString alloc] initWithFormat:@"%d", timeTick];
    labelTime.text = timeString;



}


@end

提前致谢!

1 个答案:

答案 0 :(得分:0)

你的timeTicktimer实际上是全局的,可能不是你想要的。您应该将它们声明为实例变量。这将允许您拥有TimeController的多个实例,并让它们全部独立计算。

然后你的代码看起来像这样

@interface TimeController ()

@property (nonatomic, assign) NSInteger  minutes;
@property (nonatomic, strong) NSTimer   *timer;

@end

@implementation TimeController

- (void)viewDidLoad
{
  [super viewDidLoad];
  [self updateMinuteLabel];
}

- (IBAction)startTimer
{
  [self.timer invalidate];
  self.timer = [NSTimer scheduledTimerWithTimeInterval:60.0 
                                                target:self 
                                              selector:@selector(tick) 
                                              userInfo:nil
                                               repeats:YES];
}

- (IBAction)stopTimer
{
  [self.timer invalidate];
}

- (IBAction)resetTimer
{
  self.minutes = 0;
  [self updateMinuteLabel];
}

- (void)tick
{
  self.minutes += 1;
  [self updateMinuteLabel];
}

- (void)updateMinuteLabel
{
  self.minuteLabel.text = [NSString stringWithFormat:@"%d", self.minutes];
}

@end