2012-07-08 84 views
1

我最近做了一個秒錶應用程序,它有一些故障。秒錶故障

如果我連續兩次點擊停止按鈕,整個應用程序將崩潰。

如果我連續兩次點擊啓動按鈕,計時器將運行兩次,停止按鈕將停止工作。

我該如何解決這個問題?

這裏是我的.h文件中的代碼:

IBOutlet UILabel *time; 
    IBOutlet UILabel *time1; 
    IBOutlet UILabel *time2; 

    NSTimer *myTicker; 
    NSTimer *myTicker2; 
    NSTimer *myTicker3; 
} 

- (IBAction)start; 
- (IBAction)stop; 
- (IBAction)reset; 


- (void)showActivity; 
- (void)showActivity1; 
- (void)showActivity2; 

@end 

,這裏是我的.m文件代碼:

- (IBAction)start { 
    myTicker = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(showActivity) userInfo:nil repeats:YES]; 

    myTicker2 = [NSTimer scheduledTimerWithTimeInterval:.1 target:self selector:@selector(showActivity1) userInfo:nil repeats:YES]; 

    myTicker3 = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(showActivity2) userInfo:nil repeats:YES];   
} 

- (IBAction)stop { 
    [myTicker invalidate]; 
    [myTicker2 invalidate]; 
    [myTicker3 invalidate]; 
} 

- (IBAction)reset {  
    time.text = @"00"; 
    time1.text = @"00"; 
    time2.text = @"00"; 
} 

- (void)showActivity {  
    int currentTime = [time.text intValue]; 
    int newTime = currentTime + 1; 
    if (newTime == 60) { 
     newTime = 0; 
    } 
    time.text = [NSString stringWithFormat:@"%d", newTime];  
} 

- (void)showActivity1 { 
    int currentTime1 = [time1.text intValue]; 
    int newTime1 = currentTime1 + 1; 
    if (newTime1 == 10) { 
     newTime1 = 0; 
    } 
    time1.text = [NSString stringWithFormat:@"%d", newTime1];  
} 

- (void)showActivity2 { 
    int currentTime2 = [time2.text intValue]; 
    int newTime2 = currentTime2 + 1; 
    time2.text = [NSString stringWithFormat:@"%d", newTime2]; 
} 

回答

1

將停止按鈕的userInterActionEnabled屬性NO和啓動當-stop方法被觸發時,按鈕到YES。然後,當啓動-start時,將停止按鈕userInterActionEnabled設置爲YES,將開始按鈕設置爲NO

+0

其中是userInterActonEnabled? – user1510082 2012-07-08 18:47:08

+0

這是UIButton的一個屬性。像'self.myButton.userInteractionEnabled = NO'; – CodaFi 2012-07-08 19:01:52

1

您應該創建一個私有的布爾變量「isRunning」,就停止點擊或開始像時檢查:

- (IBAction)stop { 
    if(!isRunning) return; 

    [myTicker invalidate]; 
    [myTicker2 invalidate]; 
    [myTicker3 invalidate]; 

    self.isRunning = NO; 
} 

等也忽略用戶交互一般是一個好主意(如CodaFi建議)但只能對抗症狀;-)你真的應該做兩個檢查。

+0

我如何創建一個私有布爾變量「isRunning」 – user1510082 2012-07-08 18:42:47

+0

將此行添加到@interface(您還可以定義您的IBOutlets,NSTimers等):'BOOL isRunning'。而已 ;-) – tamasgal 2012-07-08 20:23:01