runloop与常驻线程

- (void)run;
- (void)runUntilDate:(NSDate *)limitDate;
- (BOOL)runMode:(NSRunLoopMode)mode beforeDate:(NSDate *)limitDate;

Puts the receiver into a permanent loop, during which time it processes data from all attached input sources.

If no input sources or timers are attached to the run loop, this method exits immediately; otherwise, it runs the receiver in the NSDefaultRunLoopMode by repeatedly invoking runMode:beforeDate:. In other words, this method effectively begins an infinite loop that processes data from the run loop’s input sources and timers. 

Manually removing all known input sources and timers from the run loop is not a guarantee that the run loop will exit. macOS can install and remove additional input sources as needed to process requests targeted at the receiver’s thread. Those sources could therefore prevent the run loop from exiting. 

If you want the run loop to terminate, you shouldn't use this method. Instead, use one of the other run methods and also check other arbitrary conditions of your own, in a loop. A simple example would be:

--------

For secondary threads, you need to decide whether a run loop is necessary, and if it is, configure and start it yourself. You do not need to start a thread’s run loop in all cases. For example, if you use a thread to perform some long-running and predetermined task, you can probably avoid starting the run loop. Run loops are intended for situations where you want more interactivity with the thread. For example, you need to start a run loop if you plan to do any of the following: 

  • Use ports or custom input sources to communicate with other threads. 

  • Use timers on the thread. 

  • Use any of the performSelector… methods in a Cocoa application. 

  • Keep the thread around to perform periodic tasks.

 

---------

  1. Put the thread to sleep until one of the following events occurs:

    • An event arrives for a port-based input source.

    • A timer fires.

    • The timeout value set for the run loop expires.

    • The run loop is explicitly woken up. 

posted @ 2023-01-10 16:12  zzfx  阅读(35)  评论(0编辑  收藏  举报