Objective-C的定时器输出

时间:2014-02-16 04:44:54

标签: objective-c uilabel nstimer uiprogressview

这个问题是我今天早些时候question的一个分支,但仍然是一个新问题。我遇到了我在.m文件中声明的定时器循环问题:

// battery level connection timer
- (void)batteryLevelTimerRun
{
    batteryLevelSecondsCount = batteryLevelSecondsCount - 1;
    int batteryLevelProgress = batteryLevelSecondsCount;

    NSString *timerOutput = [NSString stringWithFormat:@"Battery Level: %d%%", batteryLevelProgress];
    batteryLevelLabel.text = timerOutput;

    float batteryLevelProgressFloat = batteryLevelSecondsCount / 100;
    [batteryLevel setProgress:batteryLevelProgressFloat animated:YES];

    if (batteryLevelSecondsCount == 20)
    {
        batteryLevelLabel.textColor = [UIColor orangeColor];
    }
    else if (batteryLevelSecondsCount == 10)
    {
        batteryLevelLabel.textColor = [UIColor redColor];
    }
    else if (batteryLevelSecondsCount == 0)
    {
        [batteryLevelTimer invalidate];
        batteryLevelTimer = nil;
    }
}

// battery level connection timer
- (void)batteryLevelSetTimer
{
    batteryLevelSecondsCount = 100;
    batteryLevelTimer = [NSTimer scheduledTimerWithTimeInterval:9.0 target:self selector:@selector(batteryLevelTimerRun) userInfo:nil repeats:YES];
}

.h文件中,我声明:

@interface MonitoringViewController : UIViewController

{
       IBOutlet UILabel *batteryLevelLabel; 
       IBOutlet UIProgressView *batteryLevel;

       NSTimer *batteryLevelTimer;
       int batteryLevelSecondsCount;
}

我已按下[self batteryLevelTimer]按钮。当我运行代码时,我在batteryLevelLabel UILabel字段中得到了奇怪的响应。它说Battery Level: -1%。知道为什么会这样吗?我还设置UIProgressView随标签递减,这也是功能失调(设置为0),可能是因为它认为它给出的值是-1,因此默认为0(UIProgressView值从0.0到1.0) )。我在这里错过了一些数学/逻辑错误吗?

1 个答案:

答案 0 :(得分:0)

你的代码似乎没问题,在我的测试项目中运行得很好(我将按钮连接到batteryLevelSetTimer,标签按预期计数到零)。除了进度条部分 - 您应该更改行:

float batteryLevelProgressFloat = batteryLevelSecondsCount / 100;

float batteryLevelProgressFloat = batteryLevelSecondsCount / 100.0;

因为batteryLevelSecondsCount100都是整数,并且整数除法总是产生整数结果,在你的情况下它会在0和1之间变化。