详解Run Loop

2016-08-05  本文已影响66人  _叫我小贱

Run Loop


Run Loop与线程


获取Run Loop对象

//Foundation
[NSRun Loop mainRun Loop];
//Core Foundation
CFRun LoopGetMain();

Run Loop相关类

CFRun LoopRef
CFRun LoopModeRef
CFRun LoopSourceRef
CFRun LoopTimerRef
CFRun LoopObserverRef


RunLoop.png

CFRun LoopModeRef

CFRun LoopTimerRef

CFRun LoopSourceRef

CFRun LoopObserverRef

Run Loop处理逻辑:

Run Loop

Run Loop应用

  1. 启动Run Loop

    [[NSRunLoop currentRunLoop] run];
    //等于
    [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
    //等于
    [[NSRunLoop currentRunLoop] runUntilDate:[NSDate distantFuture]];
    
  2. 只在NSDefaultRunLoopMode模式下显示图片

    [self.imageView performSelector:@selector(setImage:) withObject:[UIImage imageNamed:@"placeholder"] afterDelay:3.0 inModes:@[NSDefaultRunLoopMode]];
    
  3. 常驻线程,保证线程不死

    [[NSRunLoop currentRunLoop] addPort:[NSPort port] forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] run];
    
    //或者(不推荐)
    while(flag)
    {
        [[NSRunLoop currentRunLoop] run];
    }
    
  4. 子线程定时做事情(NSTimer)

    NSTimer *time = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(<selector>) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:time forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] run];
    //或者
    NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(<selector>) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] run];
    
上一篇 下一篇

猜你喜欢

热点阅读