0

我编译了以下代码,没有明显的运行时错误;但是,当我运行它时,显示会在 00:00:01 冻结。如果我只显示秒属性,它就可以工作。有没有人看到我在这段代码中遗漏的明显疏忽?我知道开始按钮可能存在内存泄漏,但我最终会解决这个问题。

提前致谢。

#import "StopwatchViewController.h"

@implementation StopwatchViewController

- (IBAction)start{

    //creates and fires timer every second
    myTimer = [[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(showTime) userInfo:nil repeats:YES]retain];
}
- (IBAction)stop{
    [myTimer invalidate];
    myTimer = nil;
}

- (IBAction)reset{

    [myTimer invalidate];
    time.text = @"00:00:00";
}

(void)showTime{

    int currentTime = [time.text intValue];

    int new = currentTime +1;

    int secs  = new;
    int mins  = (secs/60) % 60;
    int hours = (mins/60);

    time.text = [NSString stringWithFormat:@"%.2d:%.2d:%.2d",hours, mins, secs];
}
4

2 回答 2

3

你得到 0 从

int currentTime = [time.text intValue];

因为其中的字符串text

@"00:00:00"

无法转换为int,因此每次计时器触发时,将 1 加到 0 并得到 1,然后显示。无论如何,数学都是不准确的,因为分钟和秒是“以 60 为底”* - 您需要执行与分隔小时/分钟/秒的数学相反的操作,以便再次获得总秒数。您可以只制作currentTime一个 ivar,并保留其中的总秒数。


*这不是真正的名字;我敢肯定有一个特定的词。

于 2011-05-13T23:38:03.220 回答
2
- (IBAction)start{

    currentTime = 0;

    //creates and fires timer every second
    myTimer = [[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(showTime) userInfo:nil repeats:YES]retain];
}

- (IBAction)stop{
    [myTimer invalidate];
    myTimer = nil;
}

- (IBAction)reset{

    [myTimer invalidate];
    time.text = @"00:00:00";
}

- (void)showTime{

    currentTime++;

    int secs = currentTime % 60;
    int mins = (currentTime / 60) % 60;
    int hour = (currentTime / 3600);


    time.text = [NSString stringWithFormat:@"%.2d:%.2d:%.2d",hour, mins, secs];

}
于 2011-05-16T02:32:17.450 回答