2012-10-21 53 views
0

當我按下停止按鈕停止計時器時,它會重置爲原始時間並重新開始倒計時。我到處尋找,我發現的所有東西都是「無效的」,它不起作用。我想停下來的時候停下來,標籤上顯示原來的時間。我也關掉自動計數,所以我可以嘗試釋放,它是給我的錯誤:如何停止NSTimer

0x10e20a5: movl 16(%edx), %edx EXC_BAD_ACCESS (code=2, address=0x10)

NSTimer *rockettTimer; 
int rocketCount; 

@interface FirstViewController() 
@property (strong, nonatomic) IBOutlet UILabel *rocketTimer; 

- (IBAction)stopButton:(id)sender; 
- (IBAction)startButton:(id)sender; 

@end 

@implementation FirstViewController 
@synthesize rocketTimer; 

-(void) rocketTimerRun{ 
    rocketCount = rocketCount - 1; 
    int minuts = rocketCount/60; 
    int seconds = rocketCount - (minuts * 60); 
    NSString *timerOutput = [NSString stringWithFormat:@"%d:%.2d", minuts, seconds]; 
    rocketTimer.text = timerOutput; 
} 

- (IBAction)startButton:(id)sender { 
    rocketCount = 180; 
    rockettTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(rocketTimerRun) userInfo:nil repeats:YES]; 

- (IBAction)stopButton:(id)sender { 
    [rockettTimer invalidate]; 
    //[rockettTimer release]; 
} 

- (void)viewDidLoad 
{ 


    [super viewDidLoad]; 
// Do any additional setup after loading the view, typically from a nib. 
} 

- (void)viewDidUnload 
{ 
    [self setRocketTimer:nil]; 
    [super viewDidUnload]; 
    // Release any retained subviews of the main view. 
} 

- (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation 
{ 
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) { 
     return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown); 
    } else { 
     return YES; 
    } 
} 


@end 
+1

你確定你的stopButton連接到stopButton而不是錯誤的startButton嗎?還要注意,invalidate釋放定時器,所以不要調用release和invalidate。 – rmaddy

+0

您可能希望仔細查看代碼,沒有什麼能夠防止用戶多次按下啓動按鈕,並創建多個定時器,然後再繼續參加...因此BAD_ACCESS –

回答

2

我想像你是多次按下啓動按鈕。每次調用startButton函數時,都會創建一個新的計時器並忘記舊計時器。爲了防止這種情況,我建議在創建新定時器之前立即添加[rockettTimer invalidate]

你也應該初始化rockettTimer爲零。更好的是,你應該把它變成類的成員變量,因爲現在你將無法擁有這個類的多個實例。

+0

是的,這個代碼有很多問題......重寫! –

-1

你應該嘗試使用另一種方法來初始化你的計時器。並在viewDidLoad: