objective-c - 如何停止 NSTimer

标签 objective-c ios 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

最佳答案

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

您还应该将 RockettTimer 初始化为零。更好的是,您应该将其作为该类的成员变量,因为现在您将无法拥有该类的多个实例。

关于objective-c - 如何停止 NSTimer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12995101/

相关文章:

iphone - UIWebView 中横向模式的 Youtube 视频

ios - 如何将所有值作为 NSArray 返回?来自完成 block 中的查询

ios - 后台线程上的NSTimer回调

ios - 我们如何使用自动布局在 for 循环的帮助下创建 UIlabel?

iOS 设置 NSTimer 以仅在事件/非事件页面上调用方法

objective-c - 将参数传递给由 NSTimer 调用的方法

objective-c - 访问 UITableViewCell 的 TouchBegan/Moved/Ended

ios - 发现 UIActivityViewController 支持的所有端点,如微信、KaKao、Line 等?

ios - Objective-C:在打开之前*检测键盘大小/原点?

ios - AFNetworking 参数序列化错误