【问题标题】:Stopwatch display issue秒表显示问题
【发布时间】:2011-05-13 23:32:18
【问题描述】:

我已经编译了以下代码并且没有明显的运行时错误;但是,当我运行它时,显示会在 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];
}

【问题讨论】:

    标签: objective-c ios nsstring nstimer stopwatch


    【解决方案1】:

    你从

    得到 0
    int currentTime = [time.text intValue];
    

    因为text中的字符串:

    @"00:00:00"
    

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


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

    【讨论】:

    • 我同意只记录秒数,然后格式化文本字段的显示(而不是使用文本字段的值作为模型数据)的建议。
    • 非常感谢您的建议。我不知道我为什么要做出如此愚蠢的举动。我会修改它并发布更正的版本。感谢您的帮助。
    • 如承诺的那样。再次感谢@Josh Caswell 和@Wevah 的建议。我希望这会帮助一些困惑的人。我按照 Josh 的建议创建了一个 ivar,您可以查看其余部分。
    【解决方案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];
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-18
      • 1970-01-01
      • 1970-01-01
      • 2015-03-09
      • 1970-01-01
      • 2019-02-27
      • 2014-12-07
      相关资源
      最近更新 更多