面试runLoop

iOS RunLoop实践应用

2019-03-19  本文已影响0人  num_one

1.常驻线程

#pragma mark - YYWebImageOperation 中的常驻线程
/// Network thread entry point.
+ (void)_networkThreadMain:(id)object {
    @autoreleasepool {
        [[NSThread currentThread] setName:@"com.ibireme.webimage.request"];
        NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
        [runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
        [runLoop run];
    }
}

/// Global image request network thread, used by NSURLConnection delegate.
/// 创建全局线程
+ (NSThread *)_networkThread {
    static NSThread *thread = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        thread = [[NSThread alloc] initWithTarget:self selector:@selector(_networkThreadMain:) object:nil];
        if ([thread respondsToSelector:@selector(setQualityOfService:)]) {
            thread.qualityOfService = NSQualityOfServiceBackground;
        }
        [thread start];
    });
    return thread;
}

2.图片延迟加载(滑动时不加载)

#pragma mark - 图片延迟加载
- (void)imageViewLoad{
    //ImageView的显示 滑动时不加载 只在NSDefaultRunLoopMode模式下显示图片
    UIImageView *img;
    [img performSelector:@selector(setImage:) withObject:[UIImage imageNamed:@"placeholder"] afterDelay:3.0 inModes:@[NSDefaultRunLoopMode]];
}

3.定时器

-(void)timer{
    //在30分钟内,每隔30s执行 run 方法
    NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
    NSTimer * udpateTimer = [NSTimer timerWithTimeInterval:30
                                                    target:self
                                                  selector:@selector(run) 
                                                  userInfo:nil
                                                   repeats:YES];
    [runLoop addTimer:udpateTimer forMode:NSRunLoopCommonModes];
}

定时器尽可能使用 dis

- (void)dispatchTimer {
    // 全局队列
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    // 创建 timer
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    // 设置 timer 参数:timer,开始时间,间隔时间,时间误差
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    // timer 执行的事件
    dispatch_source_set_event_handler(timer, ^{
        <#code to be executed when timer fires#>
    });
    // 执行 timer
    dispatch_resume(timer);
}
上一篇 下一篇

猜你喜欢

热点阅读