0

以下方法会导致崩溃。UI 就像一个按钮,它处理 NSTimer 的启动/停止功能。如果计时器运行,则更新 UILabel。使用 viewDidLoad 方法使我的计时器工作,停止它也工作,但再次启动它会使应用程序崩溃。

删除 viewDidLoad 方法中的 alloc 并尝试使用开始按钮会立即导致崩溃。连theNSLog(@"Start now");都不叫。

代码:

- (void)tick {
NSLog(@"tick");
float value = [moneyLabel.text floatValue];
moneyLabel.text = [NSString stringWithFormat:@"%f", value + 1.0];

}

- (IBAction)startStopButtonClicked:(UIButton *)sender {
if ([sender.titleLabel.text isEqualToString:@"Start"]) {
    NSLog(@"Start now");
    if (timer) {
        NSLog(@"Timer valid");
        [timer fire];
    } else {
        NSLog(@"Timer is nil");
        timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(tick) userInfo:nil repeats:YES];
        [timer fire];
    }

    NSLog(@"bla");

    [sender setTitle:@"Stop" forState:UIControlStateNormal];
} else {
    [timer invalidate];
    timer = nil;
    NSLog(@"Stopped.");
    NSLog(@"Timer isValid: %@", timer);
    [sender setTitle:@"Start" forState:UIControlStateNormal];
}
}
4

2 回答 2

3

我认为根本不需要打电话[NSTimer fire];它应该足以让计时器决定何时触发。

首先确保它timernil(如果它是对象的实例变量应该是),尽管明确地将它设置为nilin- (id)init不会受到伤害。

接下来,我将使用计时器本身的状态来确定是否按下了启动/停止,而不是按钮中的文本:

- (IBAction)startStopButtonClicked:(UIButton *)sender
{
    if (timer != nil)
    {
        NSLog(@"Stopping timer");
        [timer invalidate];
        timer = nil;
    }
    else
    {
        NSLog(@"Starting timer");
        timer = [NSTimer scheduledTimerWithTimeInterval:1
                                                 target:self
                                               selector:@selector(tick)
                                               userInfo:nil
                                                repeats:YES];
    }

    [sender setTitle:(timer != nil ? @"Stop" : @"Start")
            forState:UIControlStateNormal];
}
于 2012-05-04T08:27:30.387 回答
0

The code you have posted works as desired - just tested it in a new project, so the problem could be somewhere else. I tested it only by declaring the ivar NSTimer *timer; without any initialization in viewDidLoad: or the designated initializers...

于 2012-05-04T08:41:40.700 回答