So on this page there is an example about background execution: https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html#//apple_ref/doc/uid/TP40007072-CH4-SW1, here is the example:
- (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;
});
}
It is said that bgTask is defined in class as variable. So there is one bgTask property for every instance of class (object). If applicationDidEnterBackground were to be called multiple times before async block finishes, isn't here danger of race condition? I mean bgTask would change its value, and endBackgroundTask would be called on new task value, instead of old value?
Isn't here a better solution to do this:
__block UIBackgroundTaskIdentifier bgTask;
before calling beginBackgroundTaskWithName?