如何停止NSTimer

时间:2012-10-21 04:56:11

标签: objective-c ios nstimer

当我按下停止按钮以停止定时器时,它只会重置为原始时间并再次开始倒计时。我到处寻找,我找到的只是"无效"它不起作用。当我点击停止并且标签显示原始时间时,我希望时间停止。我也关闭了自动计数,所以我可以尝试释放,它给了我一个错误:

  

0x10e20a5:movl 16(%edx),%edx EXC_BAD_ACCESS(代码= 2,地址= 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

2 个答案:

答案 0 :(得分:2)

我想你是多次按下开始按钮。每次调用startButton函数时,它都会创建一个新计时器并忘记旧计时器。为了防止这种情况,我建议您在创建新计时器之前立即放置[rockettTimer invalidate]

您还应该将rockettTimer初始化为nil。更好的是你应该把它变成类的成员变量,因为现在你将无法拥有这个类的多个实例。

答案 1 :(得分:-1)

您应该尝试使用其他方法初始化计时器。并在viewDidLoad中执行: