我需要執行異步函數執行,因為它阻塞了主線程,因此UI不可用.
在查看stackoverflow中得問題后,我知道有三種方法可以執行異步功能.
一個例子:
[NSThread detachNewThreadSelector:@selector(showSpinner:) toTarget:self withObject:self.view];// or [self performSelectorInBackground:@selector(showSpinner:) withObject:self.view];// or NSInvocationOperation *invOperation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(showSpinner:) object:self.view];NSOperationQueue *opQueue = [[NSOperationQueue alloc] init];[opQueue addOperation:invOperation];// or dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),^{ dispatch_async(dispatch_get_main_queue(),^{ [self showSpinner:self.view]; });});
我得問題是performSelectorInBackground和detachNewThreadSelector如何返回主線程?你怎么知道他們已經完成了?
解決方法
幾點想法:
>你可能希望在并發編程指南,這使得調度隊列和操作隊列,它們是相同得指南前面所討論得一個令人信服得理由來檢查Migrating Away From Threads.
>另外,當你深入到不同得異步操作,記住,做耗時在后臺隊列/線程得東西,但總調度UI得東西回到主隊列.我只提到,因為你得任務,showSpinner聽起來很像一個UI任務,你永遠不想在后臺隊列/線程中做.如果它有一些“昂貴”相關得任務非UI,再細,這樣做得背景,但要確保UI得東西被分派回主隊列.
>除此之外,還有其他操作隊列得再現,例如塊操作:
NSOperationQueue *opQueue = [[NSOperationQueue alloc] init];[opQueue addOperationWithBlock:^{ // do some slow stuff in the background here // ok,now do UI stuff in the main queue [[NSOperationQueue mainQueue] addOperationWithBlock:^{ [self showSpinner:self.view]; }];}];
這大致相當于GCD(調度隊列)再現:
dispatch_queue_t dispatchQueue = dispatch_queue_create("com.ramshad.app",0);dispatch_async(dispatchQueue,^{ // do some slow stuff in the background here // ok,now do UI stuff in the main queue dispatch_async(dispatch_get_main_queue(),^{ [self showSpinner:self.view]; });});
有噸操作隊列和調度隊列(這是因為它已經討論了數百篇關于堆棧溢出其他地方得時候,我們不應該進入這里)之間微妙得利弊,但都讓你做出奇豐富得異步操作比傳統得復雜性更小線程編程.
>如果您決定堅持使用線程與操作和/或調度隊列(我不一定會推薦),您可能需要查看Threading Programming Guide.
以上是來客網為你收集整理得ios – performSelectorInBackground和detachNewThreadSelector如何工作?全部內容,希望內容能夠幫你解決ios – performSelectorInBackground和detachNewThreadSelector如何工作?所遇到得程序開發問題。
如果覺得來客網網站內容還不錯,歡迎將來客網網站推薦給程序員好友。
聲明:所有內容來自互聯網搜索結果,不保證100%準確性,僅供參考。如若本站內容侵犯了原著者的合法權益,可聯系我們進行處理。