1
头图

An ability to monitor sub-threads to manipulate UI, and you can also add custom APIs for monitoring (to capture specific stack information when sub-threads monitor certain APIs to help locate problems)

Background introduction

Some people may have never encountered a bunch of logs output from the Xcode console during the development phase because of operating the UI in the sub-thread, which is roughly as follows

In fact, we can call Xcode Runtime Issue Breakpoint and select Main Thread Checker as the type. When the sub-thread operates the UI, it will be detected by the system and a breakpoint will be triggered, and the stack can be seen at the same time.

The effect is as follows

Problems and Solutions

The above functions are built in Xcode and only available when connected to Xcode for debugging. Online packages cannot be detected.

After exploring, the realization of this function by Xcode depends on the libMainThreadChecker.dylib library on the device. We can force the loading of this library through the dlopen method so that the non-Xcode environment also has the monitoring function.

In addition, when the UI call is monitored by the sub-thread, in the Xcode environment, the call stack will be output to the console. After testing, libMainThreadChecker.dylib is used for output. Since NSLog outputs the information to STDERR , we can pass NSPipe Intercept the output of STDERR with dup2 , and then obtain the monitored UI calls by judging the copy of the information, and finally print them out through the stack, which can help locate specific problems.

libMainThreadChecker.dylib library has limitations, and only calls to specific APIs of some specific classes provided by the system will be monitored in sub-threads (for example, the UIView class in the UIKit framework).
But some classes and some APIs we don't want to be called in the child thread, at this time libMainThreadChecker.dylib can't be satisfied.

The research on the assembly code of the libMainThreadChecker.dylib library shows that libMainThreadChecker.dylib registers classes and methods through the internal __main_thread_add_check_for_selector method. So if we can also call this method through dlsym , in order to achieve the main thread call monitoring of custom classes and methods.

In addition, this function can be turned on in the offline debug stage to determine whether it is in the Xcode debug state, which can be realized by the official judgment method by Apple.

For those who are unfamiliar with dlopen , dlsym , you can directly read Apple's official documents, which will not be expanded here.

APM Collection

For small partners who are interested in APM, you can check this article takes you to build an APM monitoring system


杭城小刘
1.1k 声望5.1k 粉丝

95 - iOS - 养了4只布偶猫