在多執行緒環境中,UI 更新必須回到主執行緒執行。performSelectorOnMainThread:withObject:waitUntilDone: 就是最直接的作法之一。
- (void)performSelectorOnMainThread:(SEL)aSelector
withObject:(id)arg
waitUntilDone:(BOOL)wait
官方說明:以預設模式在主執行緒中呼叫接收者的方法。
Invokes a method of the receiver on the main thread using the default mode.
aSelector
指定要呼叫的方法。該方法不應有意義的回傳值,並且最多只有一個 id 型別的參數,或者完全沒有參數。
A selector that identifies the method to invoke. The method should not have a significant return value and should take a single argument of type id, or no arguments.
arg
傳給該方法的參數。若方法不接受參數,傳 nil。
The argument to pass to the method when it is invoked. Pass nil if the method does not take an argument.
wait
一個布林值,指定是否要阻塞當前執行緒,直到指定的 selector 在主執行緒執行完畢。設為 YES 會阻塞當前執行緒;設為 NO 則本方法立刻回傳。
A Boolean that specifies whether the current thread blocks until after the specified selector is performed on the receiver on the main thread.
特別注意:如果當前執行緒本身就是主執行緒,且 wait 傳 YES,訊息會立即派發並處理,不會進入佇列等待。
你可以用這個方法把訊息投遞到應用程式的做主執行緒。主執行緒涵蓋應用的主 run loop,也是 NSApplication 接收事件的地方。此處的「訊息」就是你想在該執行緒上執行的當前物件方法。
You can use this method to deliver messages to the main thread of your application.
本方法會以 common modes 把訊息加入主執行緒的 run loop 佇列,也就是與 NSRunLoopCommonModes 相關的模式集合。作為正常 run loop 處理的一部分,主執行緒會從佇列中取出訊息並呼叫對應方法。從同一個執行緒多次呼叫此方法,會導致相應的 selector 依呼叫順序排隊執行。
This method queues the message on the run loop of the main thread using the common run loop modes.
你無法取消用這個方法排入佇列的訊息。若需要保留取消的能力,必須改用 performSelector:withObject:afterDelay: 或 performSelector:withObject:afterDelay:inModes:,再用 cancelPreviousPerformRequestsWithTarget: 取消。
這個方法會向當前內容的 run loop 註冊,並依賴該 run loop 被定期執行才能正確運作。一個常見的陷阱是:當你在 dispatch queue 上呼叫它時,實際註冊到的 run loop 可能並不會被自動定期驅動(例如 GCD 的工作執行緒預設沒有 run loop)。如果你在 dispatch queue 上需要類似的能力,應該改用 dispatch_after 與相關方法。
This method registers with the runloop of its current context, and depends on that runloop being run on a regular basis to perform correctly.
若只是單純要更新 UI,現在更常見的寫法是:
dispatch_async(dispatch_get_main_queue(), ^{
self.label.text = @"done";
});
兩者的差別在於:performSelectorOnMainThread: 只能傳一個 id 參數,且方法簽名受限;而 GCD 的 block 可以捕捉任意上下文,寫法也更直觀。另外,performSelector: 家族在 ARC 下會引發 -Warc-performSelector-leaks 警告,因為編譯器無法確定 selector 的所有權語意。
不過在需要與 run loop mode 互動的場景(例如要在 tracking mode 下也能收到回呼,避免拖曳滾動時停止更新),performSelectorOnMainThread: 搭配 common modes 的行為反而更方便。