秒表显示问题
我编译了以下代码,没有明显的运行时错误;但是,当我运行它时,显示冻结在 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];
}
I have compiled the following code and there are no apparent runtime errors; however, the display freezes at 00:00:01 when I run it. It works if I only display the seconds attribute. Does anyone see an apparent oversight that I have missed in this code? I know there is a potential memory leak with the start button, but I will fix that eventually.
Thanks in advance.
#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];
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您得到 0 是
因为
text
: 中的字符串无法转换为
int
,因此每次计时器触发时,您都会将 1 添加到 0 并得到1,然后将其显示。无论如何,数学都是不准确的,因为分钟和秒是“base-60”*——您需要执行与分隔小时/分钟/秒的数学相反的操作,才能再次获得总秒数。您可以将 currentTime 设为 ivar,并在其中保留总秒数。*这并不是它真正的名字;我确信有一个特定的词来形容它。
You're getting 0 from
because the string that's in
text
:can't be converted to an
int
, so every time the timer fires, you add 1 to 0 and get 1, which you then display. The math would be inaccurate anyways, because minutes and seconds are "base-60"* -- you'd need to do the reverse of the math you perform for separating hours/minutes/seconds, in order to get the total seconds again. You could just makecurrentTime
an ivar, and keep the total number of seconds in it.*That's not really what it's called; I'm sure there's a specific word for it.