【发布时间】:2017-08-24 01:44:09
【问题描述】:
苹果给this of background execution:
- (void)applicationDidEnterBackground:(UIApplication *)application
{
bgTask = [application beginBackgroundTaskWithName:@"MyTask"
expirationHandler:^{
// Clean up any unfinished task business by marking where you
// stopped or ending the task outright.
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
// Start the long-running task and return immediately.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Do the work associated with the task, preferably in chunks.
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
});
}
这个示例对我来说从来没有多大意义,我已经看到它被复制到许多后台应用程序示例中。
首先没有意义的是expirationHandler中的这两行:
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
bgTask 在块中捕获时似乎没有值。编译器这样抱怨。然后在 dispatch_async 下面的示例中显示了相同的两行。我希望它在 dispatch_async 中,但不在块中。谁能解释为什么我们在块中有这些行?
beginBackgroundTaskWithName 的文档还说“标志着一个新的长期运行的后台任务的开始。”它究竟是如何做到的?什么定义了任务?块范围内是否有任何代码?
【问题讨论】:
-
It seems like bgTask won't have a value when captured in the block.为什么不呢?苹果还声明:The bgTask variable is a member variable of the class that stores a pointer to the current background task identifier and is initialized prior to its use in this method. -
您可能将后台任务标识符与块混淆了。因此,您可能已经在不持久的范围内声明了标识符。标识符应该在 AppDelegate 中声明为成员变量,只要您的应用程序还活着,它就会一直存在。这就是为什么过期处理程序和 dispatch_async 都可以访问它而无需“复制它”。
-
@Pochi,不,我没有将标识符与块 ^ 混淆。我所做的是不小心在本地范围内声明它并离开 __block 产生警告“变量'bgTask'在被块捕获时未初始化',但我可能不应该像你说的那样在本地范围内声明它。我引用了这个:hayageek.com/ios-background-task
-
@william:是的,感谢您指出这一点。
标签: ios objective-c