1. 合适的地方添加一个子线程
[NSThread detachNewThreadSelector: @selector(newThreadProcess)
toTarget: self
withObject: nil];
2. 添加监控方法
- (void)newThreadProcess
{
@autoreleasepool {
//获得当前thread的Runloop
NSRunLoop *mainLoop = [NSRunLoop mainRunLoop];
NSRunLoop* myRunLoop = [NSRunLoop currentRunLoop];
//设置Run loop observer的运行环境
CFRunLoopObserverContext context = {0,(__bridge void *)(self),NULL,NULL,NULL};
//创建Run loop observer对象
//第一个参数用于分配observer对象的内存
//第二个参数用以设置observer所要关注的事件,详见回调函数myRunLoopObserver中注释
//第三个参数用于标识该observer是在第一次进入runloop时执行还是每次进入run loop处理时均执行
//第四个参数用于设置该observer的优先级
//第五个参数用于设置该observer的回调函数
//第六个参数用于设置该observer的运行环境
CFRunLoopObserverRef observer =CFRunLoopObserverCreate(kCFAllocatorDefault,kCFRunLoopAllActivities, YES, 0, &myRunLoopObserver, &context);
if(observer)
{
//将Cocoa的NSRunLoop类型转换成CoreFoundation的CFRunLoopRef类型
CFRunLoopRef cfRunLoop = [mainLoop getCFRunLoop];
//将新建的observer加入到当前thread的runloop
CFRunLoopAddObserver(cfRunLoop, observer, kCFRunLoopDefaultMode);
}
[myRunLoop runUntilDate:[NSDate distantFuture]];
}
}
3. 监控方法
void myRunLoopObserver(CFRunLoopObserverRef observer,CFRunLoopActivity activity,void *info)
{
switch (activity) {
//The entrance of the run loop, before entering the event processing loop.
//This activity occurs once for each callto CFRunLoopRun and CFRunLoopRunInMode
case kCFRunLoopEntry:
NSLog(@"run loop entry");
break;
//Inside the event processing loop before any timers are processed
case kCFRunLoopBeforeTimers:
NSLog(@"run loop before timers");
break;
//Inside the event processing loop before any sources are processed
case kCFRunLoopBeforeSources:
NSLog(@"run loop before sources");
break;
//Inside the event processing loop before the run loop sleeps, waiting for a source or timer to fire.
//This activity does not occur ifCFRunLoopRunInMode is called with a timeout of 0 seconds.
//It also does not occur in a particulariteration of the event processing loop if a version 0 source fires
case kCFRunLoopBeforeWaiting:
NSLog(@"run loop before waiting");
break;
//Inside the event processing loop after the run loop wakes up, but before processing the event that woke it up.
//This activity occurs only if the run loopdid in fact go to sleep during the current loop
case kCFRunLoopAfterWaiting:
NSLog(@"run loop after waiting");
break;
//The exit of the run loop, after exiting the event processing loop.
//This activity occurs once for each callto CFRunLoopRun and CFRunLoopRunInMode
case kCFRunLoopExit:
NSLog(@"run loop exit");
break;
/*
A combination of all the precedingstages
case kCFRunLoopAllActivities:
break;
*/
default:
break;
}
}
可以通过kCFRunLoopBeforeWaiting和kCFRunLoopAfterWaiting的时间差,可以得知一次runloo的时间,然后就处理时间规则。