2014-02-28 25 views
0

我得到了一個無符號整數的定時器。但是當它減去1時,它的值是零,它顯示一個正數。像這樣:http://prntscr.com/2wkydb。 這裏是我的代碼Viewcontroller.m:顯示一個int。我得到一個正數,當我減去1時,值爲0

-(IBAction)btnUp:(id)sender 
{ 
    timer = timer + 1; 
    lblTimer.text = [NSString stringWithFormat:@"%u", timer]; 
} 
-(IBAction)btnDown:(id)sender 
{ 
    timer = timer - 1; 
    lblTimer.text = [NSString stringWithFormat:@"%u", timer]; 
} 
-(IBAction)btnRestart:(id)sender 
{ 
    lblTimer.text = [NSString stringWithFormat:@"0"]; 
} 

Viewcontroller.h:

@interface ViewController : UIViewController 
{ 
    unsigned int timer; 
    IBOutlet UILabel *lblTimer; 
} 
-(IBAction)btnUp:(id)sender; 
-(IBAction)btnDown:(id)sender; 
-(IBAction)btnRestart:(id)sender; 

@end 

什麼我需要做的,因此不顯示正數,但計時器停留在0? 在此先感謝。

編輯:我也不希望計時器顯示負值。

+0

使用簽名者INT。 – Larme

+0

我也不希望數字是負數。 – Bas

+1

@Bas然後檢查它是否爲零,然後從中減去1。 –

回答

2

無符號整數「環繞」。從0中減去1給出了(假設32位整數):

0xFFFFFFFF = 4294967295 

如果你不希望你的代碼更改爲:

if (timer > 0) 
    timer = timer - 1; 

更妙的是,禁用「向下」按鈕,當數值達到零時,使能 它再次當數值爲正時。

喜歡的東西(未經測試,沒有編譯器檢查):

-(IBAction)btnUp:(UIButton *)sender 
{ 
    timer = timer + 1; 
    lblTimer.text = [NSString stringWithFormat:@"%u", timer]; 
    self.downButton.enabled = YES; 
} 
-(IBAction)btnDown:(UIButton *)sender 
{ 
    timer = timer - 1; 
    lblTimer.text = [NSString stringWithFormat:@"%u", timer]; 
    sender.enabled = (timer > 0); 
} 
+0

謝謝,啞巴,我沒有想過:) – Bas

+0

當計時器達到0,你按下按鈕保持禁用,我怎麼能再次啓用按鈕?我是新來的客觀-c – Bas

+0

@Bas:我的代碼示例中有一個錯誤,我現在已經修復了。 'btnUp'方法當然必須再次啓用「向下按鈕」。 –

相關問題