我在后台关闭应用程序时遇到了问题。在后台工作时,点按2x并滑动应用程序关闭它,应用程序不会调用applicationWillTerminate:(UIApplication *)application
,而是转到@autoreleasespool
,这绝对是崩溃。
我想它与 working 相关NSTimer
,因为没有初始化它,应用程序会从后台正确关闭。
我想NSTimer
在 appDelegate 中禁用,但没有成功,因为NSTimer
只能从同一个线程禁用。
我在班级的 init 中启动 NSTtimer:
[NSTimer scheduledTimerWithTimeInterval:5.0f target:self selector:@selector(checkLastSeenTimeofPeripheral) userInfo:nil repeats:YES];
我想在使用此处给出的答案进入后台时停止它,但它似乎仍然没有停止计时器并且应用程序在终止时崩溃。
编辑:
在 myClass 中初始化
- (id)init {
self = [super init];
if(self){
//check the connection timer
[self startCheckLastSeenTimeOfPeripheralTimer];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stopCheckLastSeenTimeOfPeripheralTimer) name:UIApplicationDidEnterBackgroundNotification object:[UIApplication sharedApplication]];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(startCheckLastSeenTimeOfPeripheralTimer) name:UIApplicationWillEnterForegroundNotification object:[UIApplication sharedApplication]];
启动/停止计时器的方法
-(void)startCheckLastSeenTimeOfPeripheralTimer {
_checkLastSeenTimeOfPeripheralTimer = [NSTimer scheduledTimerWithTimeInterval:5.0f
target:self
selector:@selector(checkLastSeenTimeofPeripheral)
userInfo:nil
repeats:YES];
NSLog(@"checkLastSeenTimeofPeripheralTimer started");
}
-(void)stopCheckLastSeenTimeOfPeripheralTimer {
if (_checkLastSeenTimeOfPeripheralTimer) {
[_checkLastSeenTimeOfPeripheralTimer invalidate];
_checkLastSeenTimeOfPeripheralTimer = nil;
NSLog(@"checkLastSeenTimeofPeripheralTimer stopped");
}
else {
NSLog(@"checkLastSeenTimeofPeripheralTimer not initialized - can't stop");
}
}