Runloop加载本地大图

本文介绍了如何通过监听Runloop来优化加载本地大图的过程,详细讲解了在不同Runloop状态下如何进行Cell的绘制,提供了一个GitHub源代码链接以供参考。
摘要由CSDN通过智能技术生成

源代码在github上。https://github.com/WiKi123/runloop-image 欢迎大家指点。


首先我们先监听当前runloop。然后根据runloop的状态进行cell的绘制。

- (void)addRunloopObserver{
    
    //获取当前的runloop
    CFRunLoopRef runloop = CFRunLoopGetCurrent();
    //定义一个上下文
    CFRunLoopObserverContext  context = {
        0,
        (__bridge void *)self,
        &CFRetain,
        &CFRelease,
        NULL,
    };
    //定义一个观察者
    static CFRunLoopObserverRef defaultModeObserver;
    //创建观察者
    defaultModeObserver = CFRunLoopObserverCreate(NULL, kCFRunLoopBeforeWaiting, YES, NSIntegerMax, &Callback, &context);
    //添加当前runloop的观察者
    CFRunLoopAddObserver(runloop, defaultModeObserver, kCFRunLoopDefaultMode);
    //释放
    CFRelease(defaultModeObserver);
    

}
当绘制cell上的img的时候,添加一个任务task。

-(void)addTask:(RunloopBlock)unit withKey:(id)key{
    
    [self.tasks addObject:unit];
    [self.tasksKeys addObject:key];

   //保证之前没有显示出来的任务。不再浪费时间加载
    if (self.tasks.count > self.maxQueueLength ) {
        [self.tasks removeObjectAtIndex:0];
        [self.tasksKeys removeObjectAtIndex:0];

    }
    
}

创建一个NSTimer,频繁的根据runloop的观察者回调方法。

_timer = [NSTimer scheduledTimerWithTimeInterval:0.001 target:self selector:@selector(timerMethod) userInfo:nil repeats:YES];

在回调方法中,进行cell上的img的绘制

static void Callback(CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info){

    ViewController *vc = (__bridge ViewController*)info;
    if (vc.tasks.count == 0) {
        return;
    }
    BOOL result = NO;
    while (result == NO && vc.tasks.count ) {
        
        //取出任务
        RunloopBlock unit = vc.tasks.firstObject;
        //执行任务
         result = unit();  //YES.所以说只执行了一次。
        //干掉第一个任务
        [vc.tasks removeObjectAtIndex:0];
        //干掉标示
        [vc.tasksKeys removeObjectAtIndex:0];
        
    }
    
}

在cell上的操作

  [self addTask:^BOOL{
        [ViewController addImg1WithCell:cell];
        return YES;
    } withKey:indexPath];
    
    [self addTask:^BOOL{
        [ViewController addImg2WithCell:cell];
        return YES;
    } withKey:indexPath];
    
    [self addTask:^BOOL{
        [ViewController addImg3WithCell:cell];
        return YES;
    } withKey:indexPath];



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值