performSelector:withObject:afterDelay: 在子執行緒中呼叫不執行

CocoaJason發表於2019-04-25

官網文件

Discussion This method sets up a timer to perform the aSelector message on the current thread’s run loop. The timer is configured to run in the default mode (NSDefaultRunLoopMode). When the timer fires, the thread attempts to dequeue the message from the run loop and perform the selector. It succeeds if the run loop is running and in the default mode; otherwise, the timer waits until the run loop is in the default mode.
If you want the message to be dequeued when the run loop is in a mode other than the default mode, use the performSelector:withObject:afterDelay:inModes: method instead. If you are not sure whether the current thread is the main thread, you can use the performSelectorOnMainThread:withObject:waitUntilDone: or performSelectorOnMainThread:withObject:waitUntilDone:modes: method to guarantee that your selector executes on the main thread. To cancel a queued message, use the cancelPreviousPerformRequestsWithTarget: or cancelPreviousPerformRequestsWithTarget:selector:object: method.

討論 此方法設定一個計時器,以在當前執行緒的執行迴圈上執行aSelector訊息。計時器配置為以預設模式(NSDefaultRunLoopMode)執行。當計時器觸發時,執行緒會嘗試將訊息從執行迴圈中出列並執行選擇器。如果執行迴圈正在執行且處於預設模式,它會成功;否則,計時器等待直到執行迴圈處於預設模式。
如果希望在執行迴圈處於預設模式以外的模式時將訊息出列,請使用performSelector:withObject:afterDelay:inModes:方法。如果您不確定當前執行緒是否是主執行緒,則可以使用performSelectorOnMainThread:withObject:waitUntilDone:或performSelectorOnMainThread:withObject:waitUntilDone:modes:方法來保證您的選擇器在主執行緒上執行。要取消排隊的訊息,請使用cancelPreviousPerformRequestsWithTarget:或cancelPreviousPerformRequestsWithTarget:selector:object:方法。

Special Considerations This method registers with the runloop of its current context, and depends on that runloop being run on a regular basis to perform correctly. One common context where you might call this method and end up registering with a runloop that is not automatically run on a regular basis is when being invoked by a dispatch queue. If you need this type of functionality when running on a dispatch queue, you should use dispatch_after and related methods to get the behavior you want.

特別注意事項 此方法向其當前上下文的runloop註冊,並依賴於定期執行的runloop以正確執行。 您可以呼叫此方法並最終使用不會自動定期執行的runloop註冊的一個常見上下文是由排程佇列呼叫。 如果在排程佇列上執行時需要此類功能,則應使用dispatch_after和相關方法來獲取所需的行為。

相關文章