NSTimer 并在后台关闭应用程序

NSTimer and closing app while in background

我在后台关闭应用程序时遇到了问题。 在后台工作时,点击2x并滑动应用程序关闭它,应用程序不会调用applicationWillTerminate:(UIApplication *)application,而是转到@autoreleasespool,这肯定是崩溃。

我想它与工作有关 NSTimer,因为如果不初始化它,应用程序会从后台正常关闭。

我想在 appDelegate 中禁用 NSTimer 但没有成功,因为 NSTimer 只能从同一个线程中禁用。

我正在 class 的初始化中启动 NSTtimer:

[NSTimer scheduledTimerWithTimeInterval:5.0f target:self selector:@selector(checkLastSeenTimeofPeripheral) userInfo:nil repeats:YES];

我想在使用 answer given here 进入后台时停止它,但它似乎仍然没有停止计时器并且应用程序在终止时崩溃。

编辑:

正在 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]];

start/stop 计时器的方法

-(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");
    }
}

根据 documentation 关闭暂停的应用程序时未调用 appWillTerminate:Suspended apps receive no notification when they are terminated; the system kills the process and reclaims the corresponding memory. 应用程序在后台被系统暂停而不通知它。