Five modes of Runloop

1. The runloop is an event-driven loop. It processes events when they are received, and goes to sleep when there are no events. 2.
Once the application is started, the main thread is created, and the corresponding runloop of the main thread is also created. The runloop also ensures that the program can run continuously Run. Sub-threads created later do not have a runloop by default, and are only created when [NSRunLoop currentRunLoop] is called to obtain it.
3. Runloop modes:
There are five modes in total:

  • NSDefaultRunLoopMode Default
  • UITrackingRunLoopMode UI dedicated
  • UIInitializationRunLoopMode is the first mode entered when the app is just started, and it will no longer be used after the startup is complete
  • GSEventReceiveRunLoopMode Internal Mode for accepting system events
  • NSRunLoopCommonModes This is a placeholder Mode, not a real Mode

Scenario: When a UIScrollView is added to a page and there is a timer, when the UIScrollView slides, the timer does not work,

reason:

We add the timer to the current main thread, and select the default mode of NSDefaultRunLoopMode. The default is normal execution. When the UIScrollView is slid, the UI interacts. At this time, the main thread Runloop will switch to UITrackingRunLoopMode, and the timer will stop. The
mode is similar to the runway, and a runloop can only be performed on one runway at the same time. , and the mode has priority. UITrackingRunLoopMode is the UI mode, which is the mode with the highest priority. When the runloop encounters an event, it will switch to the mode specified by the event. UITrackingRunLoopMode has the highest priority, so it switches to this Mode, events in other modes will not be executed at this time.
And UITrackingRunLoopMode can only be awakened by UI events. If the mode specified by the timer above is changed to UI mode, it will not be executed by default, but when sliding textView When running, it will switch to UI mode, and the timer can be executed. Once the sliding stops, the timer will stop again. NSRunLoopCommonModes
is essentially NSDefaultRunLoopMode and UITrackingRunLoopMode, which is equivalent to adding both modes, no matter which runway, it will Encountered timer event.


So when defining NSTimer, it is best to add it directly to NSRunLoopCommonModes,

timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timeEvent) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer: timer forMode:NSRunLoopCommonModes];

Guess you like

Origin blog.csdn.net/KLong27/article/details/132168012