2014-02-16 17 views
0

這個問題是從我以前的question從早些時候的分支,但仍然是一個新問題。我有一個計時器循環的問題,我在.m文件中聲明:Objective-C的計時器輸出

// 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 )。我在這裏錯過了一些數學/邏輯錯誤嗎?

+0

手工檢查您的代碼:'batteryLevelSecondsCount'爲0時會發生什麼? –

+0

@JoshCaswell當'batteryLevelSecondsCount'爲0時,它執行:'[batteryLevelTimer invalidate];''和'batteryLevelTimer = nil;'。我試着通過在'UIAlertView'中添加來檢查它是否調用了該操作,但它沒有啓動,這意味着'batteryLevelSecondsCount'未設置爲0. – James

+0

當'batterLevelSecondsCount'爲0時_before_會發生什麼? –

回答

0

您的代碼似乎沒問題,在我的測試項目中工作得很好(我將按鈕連接到batteryLevelSetTimer,標籤按預期計數到零)。除了進度條的一部分 - 你應該改變行:

float batteryLevelProgressFloat = batteryLevelSecondsCount/100; 

float batteryLevelProgressFloat = batteryLevelSecondsCount/100.0; 

,因爲這兩個batteryLevelSecondsCount100是整數,並且整數除法總是產生整數結果,其中0和1之間變化在你的情況。

+0

即使在將「100」更改爲「100.0」後,UIProgressView也不會改變。除此之外,你如何用'batteryLevelLabel'解釋這個問題? – James

+0

@James我認爲你應該設置一些斷點並調試你的程序,因爲你的代碼幾乎是爲我工作的(我將它移植到AppKit以避免與模擬器混淆)。在兩種方法的第一行設置BP,看看發生了什麼。 – user3125367

+0

@James或者只是'NSLog(@「%d」,batteryLevelLabel);'看看它會變成什麼值。 – user3125367