美文网首页
RunLoop相关问题

RunLoop相关问题

作者: 当优秀成为习惯 | 来源:发表于2019-01-07 10:06 被阅读11次

什么是RunLoop?

RunLoop顾名思义是运行时循环,在程序运行过程中循环做一些事情。
当有响应事件比如点击,定时器,滑动等等,Runloop就会响应。当没有事件处理的时候,RunLoop就会进入睡眠模式,这样就极大的降低了CPU资源的损耗,提高了程序的性能。

如果没有RunLoop,执行完打印就会退出程序

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        NSLog(@"Hello, World!");
    }
    return 0;
}

问题:项目中有用到Runloop

RunLoop应用范畴

  • 定时器(Timer)、PerformSelector
  • GCD Async Main Queue
  • 事件响应、手势识别、界面刷新
  • 网络请求
  • AutoreleasePool

RunLoop对象

ios有两套API来访问和使用RunLoop

  • Foundation :NSRunLoop
  • CoreFoundation:CFRunLoopRef
    NSRunLoop是基于CFRunLoopRef的一层OC包装。

获取Runloop对象相应的方法
[NSRunLoop mainRunLoop]; //获取主runloop
[NSRunLoop currentRunLoop];// 获取当前runloop对象
runloop在项目中的应用场景?

int main(int argc, char * argv[]) {
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
    }
}

应用程序的入口创建了runloop对象,这也保证了程序能够一直运行。
定时器

  [[NSRunLoop currentRunLoop] addTimer:[NSTimer timerWithTimeInterval:2 repeats:YES block:nil] forMode:NSRunLoopCommonModes];

Runloop与线程

Runloop与线程一对一的关系。Runloop保存在一个全局的字典当中。其中线程是keyrunloopvalue

相关文章

网友评论

      本文标题:RunLoop相关问题

      本文链接:https://www.haomeiwen.com/subject/gpmyrqtx.html