转自:http://blog.csdn.net/lingedeng/article/details/6870692
如果你在非main
thread中运行run loop,你必须至少为该run loop添加一个input sources或timer。如果你运行的run loop没有监控任何的输入源,该run loop将在你运行后立即退出。
Run
loop observer
使用detachNewThreadSelector:toTarget:withObject:创建一个thread:
- [NSThread detachNewThreadSelector:@selector(observerRunLoop) toTarget:self withObject:nil];
在新thread的run
loop中添加observer:
- - (void)observerRunLoop {
- //建立自动释放池
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
- //获得当前thread的Run loop
- NSRunLoop *myRunLoop = [NSRunLoop currentRunLoop];
- //设置Run loop observer的运行环境
- CFRunLoopObserverContext context = {0, self, NULL, NULL, NULL};
- //创建Run loop observer对象
- //第一个参数用于分配observer对象的内存
- //第二个参数用以设置observer所要关注的事件,详见回调函数myRunLoopObserver中注释
- //第三个参数用于标识该observer是在第一次进入run loop时执行还是每次进入run loop处理时均执行
- //第四个参数用于设置该observer的优先级
- //第五个参数用于设置该observer的回调函数
- //第六个参数用于设置该observer的运行环境
- CFRunLoopObserverRef observer = CFRunLoopObserverCreate(kCFAllocatorDefault, kCFRunLoopAllActivities, YES, 0, &myRunLoopObserver, &context);
- if (observer) {
- //将Cocoa的NSRunLoop类型转换成Core Foundation的CFRunLoopRef类型
- CFRunLoopRef cfRunLoop = [myRunLoop getCFRunLoop];
- //将新建的observer加入到当前thread的run loop
- CFRunLoopAddObserver(cfRunLoop, observer, kCFRunLoopDefaultMode);
- }
- //Creates and returns a new NSTimer object and schedules it on the current run loop in the default mode
- [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(doFireTimer:) userInfo:nil repeats:YES];
- NSInteger loopCount = 10;
- do {
- //启动当前thread的loop直到所指定的时间到达,在loop运行时,run loop会处理所有来自与该run loop联系的input source的数据