【发布时间】:2015-03-11 08:19:23
【问题描述】:
我在后台关闭应用时遇到了问题。
在后台工作时,轻按2x并滑动应用关闭应用,应用不调用applicationWillTerminate:(UIApplication *)application,而是转到@autoreleasespool,这绝对是crash。
我想它与工作中的NSTimer 相关,因为没有初始化它,应用程序会从后台正常关闭。
我想在 appDelegate 中禁用 NSTimer,但没有成功,因为 NSTimer 只能从同一个线程中禁用。
我在班级的 init 中启动 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]];
启动/停止计时器的方法
-(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");
}
}
【问题讨论】:
-
你能发布你的代码吗?你在使用 appDelegate NSNotifications 吗?
-
已添加代码。是的,当应用程序进入后台时,我正在使用 NSNotifications 做出反应。
-
并且实际调用了stopCheckLastSeenTimeOfPeripheral,但是应用不关闭的问题依然存在。
-
等等,你遇到的问题是当设备连接到 Xcode 并且你正在调试时?如果您关闭您的应用程序,并且您有事件正在运行,那么显然该应用程序将崩溃。如果您在网络过程中使用任何应用程序,也会发生同样的情况。无关紧要,确保你删除了 dealloc 或 viewDidUnload 中的观察者。
-
在调试和正常使用时都会发生。在 appWillTerminate 我取消所有本地通知。在后台关闭应用程序时,它们永远不会被取消。问题与观察者无关,因为我之前没有配置它们并且问题发生了。我添加了它们以尝试停止计时器。
标签: ios xcode background nstimer close-application