0

我创建了一个简单地计时分钟的 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

提前致谢!

4

1 回答 1

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
于 2013-11-04T00:16:50.523 回答