所以在这个页面上有一个关于后台执行的例子:https ://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html#//apple_ref/doc/uid/TP40007072- CH4-SW1,示例如下:
- (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;
});
}
据说bgTask
在类中定义为变量。因此bgTask
,类(对象)的每个实例都有一个属性。如果applicationDidEnterBackground
在异步块完成之前被多次调用,这不是竞争条件的危险吗?我的意思是bgTask
会改变它的价值,并且endBackgroundTask
会被调用新的任务价值,而不是旧的价值?
这里不是更好的解决方案吗:
__block UIBackgroundTaskIdentifier bgTask;
打电话之前beginBackgroundTaskWithName
?