我想充分了解下面的代碼我在研究iOS的後臺任務後放在一起,我希望一些幫助,瞭解後臺任務執行語法和GCD
我理解基本概念,
首先我們得到應用程序單例,然後我們創建一個塊並向系統註冊後臺任務,然後最後我們異步調度要運行的任務。
因此,這裏是我尋求幫助與片:
當background_task分配塊,實際塊並沒有我們想它裏面運行的代碼,只有在清理代碼它是完成處理程序,爲什麼?
我明白dispatch_async基本上啓動一個新的線程,並開始通過塊中的代碼工作,但在這個dispatch_async請求是在哪裏引用background_task?我沒有看到系統如何理解我們想要在dispatch_async請求中執行的代碼與我們之前註冊的background_task有關。
爲什麼我們需要清理代碼在dispatch_async塊和的末尾在background_task的完成處理程序中?
很抱歉,如果這些愚蠢的問題,但我只是不明白的語法,
這裏是代碼中,我拼湊起來:
UIApplication *application = [UIApplication sharedApplication]; //Get the shared application instance
__block UIBackgroundTaskIdentifier background_task; //Create a task object
background_task = [application beginBackgroundTaskWithExpirationHandler:^{ //Register background_task
[application endBackgroundTask: background_task]; //Tell the system that we are done with the tasks
background_task = UIBackgroundTaskInvalid; //Set the task to be invalid
//Above code called when endBackgroundTask is called
}];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//Perform your tasks that your application requires
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateText) userInfo:nil repeats:YES];
NSLog(@"\n\nRunning in the background!\n\n");
[application endBackgroundTask: background_task]; //End the task so the system knows that you are done with what you need to perform
background_task = UIBackgroundTaskInvalid; //Invalidate the background_task
});
你想要別人解釋你寫的代碼嗎? – hooleyhoop
@hooleyhoop,不,我希望有人幫助解釋我明確表示我「拼湊」在一起的代碼的更詳細的細節,但感謝您的意見。 – Woodstock
我想知道你是否真的知道你在做什麼。 「後臺任務」是當用戶切換到另一個應用程序時執行的任務,通常應避免。而他們與GCD完全沒有關係,這是關於在後臺線程而不是主線程中執行的任務,而您的應用程序是活動應用程序。 – gnasher729