以下方法会导致崩溃。 UI 就像一个按钮,它处理 NSTimer 的启动/停止功能。如果计时器运行,则会更新 UILabel。使用 viewDidLoad 方法使我的计时器工作,停止它也能工作,但再次启动它会使应用程序崩溃。
删除 viewDidLoad 方法中的分配并尝试使用开始按钮会导致崩溃立即。甚至 NSLog(@"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];
}
}
最佳答案
我认为根本不需要调用 [NSTimer fire]
;它应该足以让计时器决定何时触发。
首先确保 timer
为 nil
(如果它是对象的实例变量,则应该是),尽管明确将其设置为 nil
在 - (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];
}
关于iphone - NSTimer 导致崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10445107/