为什么 NSTimer 在应用程序暂停时持续触发?
Why does NSTimer persist firing while app is suspended?
据我所知,iOS 应用程序生命周期在隐藏时有两个不同的阶段:
- 背景 - 当我们仍然能够进行计算和运行代码时;
- Suspended - 当任何计算被冻结并且我们不能做任何事情直到用户 returns 到应用程序。
所以我对下面的例子有点困惑:
- (void)applicationDidEnterBackground:(UIApplication *)application {
(void)(^expirationHandler)() = [^{
[application endBackgroundTask:bgTask];
self.bgTask = UIBackgroundTaskInvalid;
} copy];
self.bgTask = [application beginBackgroundTaskWithName:@"MyTask" expirationHandler:expirationHandler];
[NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(count)
userInfo:nil
repeats:YES];
expirationHandler();
}
- (void)count {
int i = 0;
while (i < 10000000) {
i++;
}
NSLog(@"%d", i);
}
P.S。我凭记忆复制了它,如果有问题请告诉我,但问题与代码段的正确性无关。
我在 iPhone 6+ 和 iOS 9.3 上测试了它,指定的计时器持续触发,此外计数方法执行代码(您可以通过 i
值检查它)。我认为应用程序必须在定时器预定后进入暂停状态,我说得对吗?如果是这样,为什么 count
能够执行代码?
提前致谢。
根据评论中的 @Paulw11,
Are you testing while running under the debugger in Xcode? If so, then you app doesn't have background time limits or get suspended
我还没有找到任何证据,但通过实证调查似乎是真的。
据我所知,iOS 应用程序生命周期在隐藏时有两个不同的阶段:
- 背景 - 当我们仍然能够进行计算和运行代码时;
- Suspended - 当任何计算被冻结并且我们不能做任何事情直到用户 returns 到应用程序。
所以我对下面的例子有点困惑:
- (void)applicationDidEnterBackground:(UIApplication *)application {
(void)(^expirationHandler)() = [^{
[application endBackgroundTask:bgTask];
self.bgTask = UIBackgroundTaskInvalid;
} copy];
self.bgTask = [application beginBackgroundTaskWithName:@"MyTask" expirationHandler:expirationHandler];
[NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(count)
userInfo:nil
repeats:YES];
expirationHandler();
}
- (void)count {
int i = 0;
while (i < 10000000) {
i++;
}
NSLog(@"%d", i);
}
P.S。我凭记忆复制了它,如果有问题请告诉我,但问题与代码段的正确性无关。
我在 iPhone 6+ 和 iOS 9.3 上测试了它,指定的计时器持续触发,此外计数方法执行代码(您可以通过 i
值检查它)。我认为应用程序必须在定时器预定后进入暂停状态,我说得对吗?如果是这样,为什么 count
能够执行代码?
提前致谢。
根据评论中的 @Paulw11,
Are you testing while running under the debugger in Xcode? If so, then you app doesn't have background time limits or get suspended
我还没有找到任何证据,但通过实证调查似乎是真的。