iphone - NSTimer 导致崩溃

标签 iphone ios xcode crash nstimer

以下方法会导致崩溃。 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];它应该足以让计时器决定何时触发。

首先确保 timernil(如果它是对象的实例变量,则应该是),尽管明确将其设置为 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/

相关文章:

swift - 自定义,向上滑动,在每个页面上导航 xcode

Swiftui 渐变制作器 Spacer 无用

iphone - 从包含 NSArray 的 NSMutableArray 中删除对象

iphone - NSAttributedString 能否用于将 native 应用程序操作与文字联系起来?

javascript - 添加到 iOS 主屏幕后,如何在 PWA 上下载动态生成的 PDF 文件?

ios - 具有默认操作的可滑动表格 View 单元格

ios - 在 Uitextfield 上使用 UiSearchBar 有任何真正的理由吗?

xcode 4.2.5 占用大量内存,先从一些git进程开始

ios - 使用 Apple Healthkit 测量心率

xcode - 在使用 sqlite、fmdb 和 swift 时遇到问题