Jak*_*ubM 17 cocoa-touch background nstimer runloop ios
我根本不明白它,但NSTimer在我的应用程序肯定是在后台运行.我有一个NSLog由计时器运行的mehod,它在后台进行记录.它位于带有iOS 4.2.1的iPhone 4上.我在Info.plist中声明了位置背景支持.
我在这里和其他地方阅读了文档和许多讨论,这是不可能的.这是一个iOS错误吗?还是没有文档的功能?我不想使用它并在不久的将来发现,例如随着iOS 4.3的出现,Apple默默地"修复"它并且应用程序无法正常工作.
有人知道更多吗?
Rob*_*ier 33
NSTimer每当主runloop运行时,它将会触发.苹果公司没有做出任何我不知道的承诺来安排计时器或阻止主要的runloop运行.当您搬到后台时,您有责任取消计划您的计时器并释放资源.Apple不会为你做这件事.但是,当您不应该使用或使用太多秒时,它们可能会因为跑步而杀死您.
系统中有许多漏洞,允许应用程序在未经授权的情况下运行.操作系统防止这种情况非常昂贵.但你不能依赖它.
在后台执行模式下,您可以启动计时器.有几个技巧:
beginBackgroundTaskWithExpirationHandler.- (void)viewDidLoad
{
// Avoid a retain cycle
__weak ViewController * weakSelf = self;
// Declare the start of a background task
// If you do not do this then the mainRunLoop will stop
// firing when the application enters the background
self.backgroundTaskIdentifier =
[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
[[UIApplication sharedApplication] endBackgroundTask:self.backgroundIdentifier];
}];
// Make sure you end the background task when you no longer need background execution:
// [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskIdentifier];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Since we are not on the main run loop this will NOT work:
[NSTimer scheduledTimerWithTimeInterval:0.5
target:self
selector:@selector(timerDidFire:)
userInfo:nil
repeats:YES];
// This is because the |scheduledTimerWithTimeInterval| uses
// [NSRunLoop currentRunLoop] which will return a new background run loop
// which will not be currently running.
// Instead do this:
NSTimer * timer =
[NSTimer timerWithTimeInterval:0.5
target:weakSelf
selector:@selector(timerDidFire:)
userInfo:nil
repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer
forMode:NSDefaultRunLoopMode];
// or use |NSRunLoopCommonModes| if you want the timer to fire while scrolling
});
}
- (void) timerDidFire:(NSTimer *)timer
{
// This method might be called when the application is in the background.
// Ensure you do not do anything that will trigger the GPU (e.g. animations)
// See: http://developer.apple.com/library/ios/DOCUMENTATION/iPhone/Conceptual/iPhoneOSProgrammingGuide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html#//apple_ref/doc/uid/TP40007072-CH4-SW47
NSLog(@"Timer did fire");
}
Run Code Online (Sandbox Code Playgroud)
笔记
| 归档时间: |
|
| 查看次数: |
19189 次 |
| 最近记录: |