我有一個方法,我想在-viewDidLoad
和後臺線程後調用。有沒有辦法這兩種方法相結合:如何調用延遲和後臺線程的方法
[self performSelector:(SEL) withObject:(id) afterDelay:(NSTimeInterval)]
和
[self performSelectorInBackground:(SEL) withObject:(id)]
?
我有一個方法,我想在-viewDidLoad
和後臺線程後調用。有沒有辦法這兩種方法相結合:如何調用延遲和後臺線程的方法
[self performSelector:(SEL) withObject:(id) afterDelay:(NSTimeInterval)]
和
[self performSelectorInBackground:(SEL) withObject:(id)]
?
Grand Central Dispatch有dispatch_after()
它將在指定隊列上的指定時間後執行一個塊。如果你創建一個背景隊列,你將擁有你想要的功能。
dispatch_queue_t myBackgroundQ = dispatch_queue_create("com.romanHouse.backgroundDelay", NULL);
// Could also get a global queue; in this case, don't release it below.
dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, seconds * NSEC_PER_SEC);
dispatch_after(delay, myBackgroundQ, ^(void){
[self delayedMethodWithObject:someObject];
});
dispatch_release(myBackgroundQ);
[self performSelector:(SEL) withObject:(id) afterDelay:(NSTimeInterval)]
在被調用的線程上執行選擇器。所以當你從後臺線程調用它時,它將在那裏運行...
你可以做到每例如:
dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, <delay in seconds> * NSEC_PER_SEC);
dispatch_after(delay, dispatch_get_main_queue(), ^{
[self performSelectorInBackground: <sel> withObject: <obj>]
});
莫名其妙的混合溶液。最好堅持一個完整的GCD方法。
嘗試以下操作:
// Run in the background, on the default priority queue
dispatch_async(dispatch_get_global_queue(0, 0), ^{
[self performSelector:(SEL) withObject:(id) afterDelay:(NSTimeInterval)]
});
代碼沒有測試
請注意,您的選擇/方法不能使用UIKit的(所以不要更新UI)或訪問UIKit的特性(如幀)所以你的選擇器可能需要開始工作回主線程。例如
(id)SomeMethod:UsingParams: {
// Do some work but the results
// Run in the background, on the main queue
dispatch_async(dispatch_get_main_queue(), ^{
// Do something UIKit related
});
}
+1不應該從後臺線程中觸及。 – Barjavel
的問題是,當'[自performSelector:(SEL)withObject:(ID)afterDelay:(NSTimeInterval)]'單獨在後臺線程中使用,它不是用於提的是UI運行 –