RunLoop的作用与实现

2016-06-13  本文已影响276人  Lin_梓明

一、作用

1.使程序一直运行并接收用户的输入
2.决定程序在何时处理哪些事件
3.节省CPU时间(当程序启动后,什么都没有执行的话,就不用让CPU来消耗资源来执行,直接进入睡眠状态)

runloop.png runloop示意图.png

二、模拟RunLoop的实现

void callFunc(int type) {
  NSLog(@"正在执行%d", type);
}
int main(int argc, const char * argv[]) {
    @autoreleasepool{
        int result = 0;
        while (YES)
       {
          printf("请输入选择项,0表示退出:");
          scanf("%d", &result);
          if (result ==0) {
              printf("88\n");
              break;
          } else {
              callFunc(result);
          }
      }
  }
   return 0;
}

三、定时器和RunLoop

- (void)viewDidLoad {
    [superviewDidLoad];
    NSTimer*timer =[NSTimertimerWithTimeInterval:1.0target:selfselector:@selector(fire) userInfo:nil repeats:YES];
    //添加到运行循环
    //NSDefaultRunLoopMode : 默认模式,表示应用程序空闲,绝大多数的事件响应都是在这种模式:定时器
    //UITrackingRunLoopMode : 滚动模式, 只有滚动模式下才会触发定时器回调。
    //NSRunLoopCommonModes : 默认包含1,2两种模式

    [[NSRunLoopcurrentRunLoop] addTimer:timer forMode: NSRunLoopCommonModes];
}
- (void)fire {
 // 模拟睡眠
 //在iOS9.0之前,线程休眠的时候,runLoop 不响应任何事件,开发中不建议使用。
// [NSThread sleepForTimeInterval:1.0];
   static int num = 0;
/// 耗时操作
   for (int i =0; i < 1000 * 1000; ++i) {
      [NSString stringWithFormat:@"hello - %d", i]; 
  }
   NSLog(@"%d",num++);
}

##运行测试,会发现卡顿非常严重。

将时钟添加到其他线程工作

- (void)viewDidLoad {
    [superviewDidLoad];

   NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(startTimer) object:nil];
    [thread start];
}

- (void)startTimer {
    NSLog(@"startTimer =%@",[NSThreadcurrentThread]);

    NSTimer*timer = [NSTimertimerWithTimeInterval:1.0target:selfselector:@selector(fire) userInfo:nil repeats:YES];

    //添加到运行循环
    //NSDefaultRunLoopMode : 默认模式,表示应用程序空闲,绝大多数的事件响应都是在这种模式:定时器
    //UITrackingRunLoopMode : 滚动模式, 只有滚动模式下才会触发定时器回调。
    //NSRunLoopCommonModes : 默认包含1,2两种模式
    //在实际开发中,不建议将定时器的运行循环模式设置为NSRunLoopCommonModes,在有耗时操作的时候会影响流畅度。

    [[NSRunLoopcurrentRunLoop] addTimer:timer forMode: NSRunLoopCommonModes];

    //runLoop最主要的作用:监听事件

    //每一个线程都会有一个runLoop,默认情况下,只有主线程的 runLoop 是开启的,子线程的
runLoop 是不开启。
    //启动当前线程的runLoop -- 是一个死循环
    //使用下面方法启动,没办法在某一条件成立后手动停止runLoop,只能由系统停止。
// [[NSRunLoop currentRunLoop] run];

    CFRunLoopRun();

     NSLog(@"come here");

}
- (void)fire {
    //模拟睡眠
    //在iOS9.0之前,线程休眠的时候,runLoop 不响应任何事件,开发中不建议使用。
// [NSThread sleepForTimeInterval:1.0];
   static int num = 0;

    /// 耗时操作
   for (int i =0; i < 1000 * 1000; ++i) {
     [NSString stringWithFormat:@"hello - %d", i];
    }

   NSLog(@"%d---%@", num++,[NSThread currentThread]);

   if (num == 2) {
        NSLog(@"停止RunLoop");
        // 停止RunLoop
        CFRunLoopStop(CFRunLoopGetCurrent());
    }
}

注意:主线程的运行循环是默认启动的,但是子线程的运行循环是默认不工作的。
上一篇 下一篇

猜你喜欢

热点阅读