前两天,看到一篇文章,说的是在某种卡顿方案监控下,无法监控到以下代码引起的卡顿:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
int a = 0;
NSLog(@"-->耗时操作begin");
for (long i = 0; i < 1000000000; i++) {
a = a + 1;
}
NSLog(@"耗时操作结束end<--");
}
文中所说的卡顿方案如下:
void runLoopObserverCallBack(CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info) {
NSLog(@"Runloop状态改变: %@", [[JYMonitorRunloop shared] activity:activity]);
[[JYMonitorRunloop shared] setRunLoopActivity:activity];
dispatch_semaphore_t semaphore = [JYMonitorRunloop shared].dispatchSemaphore;
dispatch_semaphore_signal(semaphore);
}
- (void)beginMointor {
[JYMonitorRunloop shared].dispatchSemaphore = dispatch_semaphore_create(0);
CFRunLoopObserverContext context = {
0, (__bridge void *)self, NULL, NULL};
self.runloopObserver = CFRunLoopObserverCreate(kCFAllocatorDefault, kCFRunLoopAllActivities, YES, 0, &runLoopObserverCallBack, &context);
// 将观察者添加到主线程runloop的common模式下的观察中
CFRunLoopAddObserver(CFRunLoopGetMain(), self.runloopObserver, kCFRunLoopCommonModes);
// 创建子线程监控
dispatch_async(dispatch_get_global_queue(0, 0), ^{
int i = 0;
while (YES) {
// 阻塞子线程,如果发现阻塞了3次, Runloop状态还不改变,说明有卡顿.
long semaphoreWait = dispatch_semaphore_wait(self->_dispatchSemaphore, dispatch_time(DISPATCH_TIME_NOW,