ios - 无效时 NSTimer 在 Iphone 上因 EXC_BAD_ACCESS 而崩溃

标签 ios objective-c iphone nstimer exc-bad-access

我在我的应用程序中设置了两个计时器,它们都每隔几秒重复一次。 一切正常,除了何时使计时器无效。 当手机锁定时,我想使这些计时器失效,然后在手机解锁时重新创建它们。

我使用通知来了解何时使计时器无效/创建计时器。

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notify_didBecomeActive:) name:UIApplicationDidBecomeActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notify_willResigneActive:) name:UIApplicationWillResignActiveNotification object:nil];

这是 notify_didBecomeActive 方法包含的内容:

clockTicker = [[NSTimer scheduledTimerWithTimeInterval: 1  
                                            target: self  
                                          selector: @selector(showActivity)  
                                          userInfo: nil  
                                           repeats: YES] retain];

alarmTicker = [[NSTimer scheduledTimerWithTimeInterval: CONST_ALARMTIMER  
                                               target: self  
                                             selector: @selector(checkAndLaunchAlarm)  
                                             userInfo: nil  
                                              repeats: YES] retain];

notify_willResigneActive 方法包含:

if (alarmTicker) {
    [alarmTicker invalidate];
    [alarmTicker release];
    alarmTicker = NULL;
}

if (clockTicker) {
    [clockTicker invalidate];
    [clockTicker release];
    clockTicker = NULL;
}

问题是,当我在第二个计时器无效时调试它时,我得到了错误。 奇怪的是,如果我切换计时器的顺序(比如首先使 clockTicker 无效)。我仍然在第二个计时器上遇到错误。

我做错了什么?

谢谢, 莱昂纳多

最佳答案

invalidate 释放定时器,失效后不需要释放,这就是它崩溃的原因。但我刚刚注意到您保留了计时器……我也不确定这是否有必要。

关于ios - 无效时 NSTimer 在 Iphone 上因 EXC_BAD_ACCESS 而崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1446156/

相关文章:

ios - 使用 Swift 将更多数据传递到 UISearchController

ios - 为什么我不能停止 NSTimer?

iphone - 处理 iPhone 应用程序中的 fatal error

ios - 如何在 iOS 中使用 GoogleMaps GMSCamera 更新或更改两个位置之间的相机位置?

ios - 如何使用 OpenCV 创建 iOS Objective-C 项目

iphone - TableViewDataSource 文件的运行时错误已分离

iphone - RestKit 应用程序因 [NSPathStore2 stringByAppendingQueryParameters :]: unrecognized selector message 而崩溃

iOS动态定义String

ios - xcode12 issus : ld :building for iOS Simulator,,但链接到为iOS构建的目标文件中,针对架构arm64的文件 'xxx.framework/xxx'

ios - 更改 iPhone UISlider 条形图