Runloop加载大图

来源:互联网 发布:java是后端吗 编辑:程序博客网 时间:2024/05/21 09:07

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

[objc] view plain copy
  1. - (void)addRunloopObserver{  
  2.       
  3.     //获取当前的runloop  
  4.     CFRunLoopRef runloop = CFRunLoopGetCurrent();  
  5.     //定义一个上下文  
  6.     CFRunLoopObserverContext  context = {  
  7.         0,  
  8.         (__bridge voidvoid *)self,  
  9.         &CFRetain,  
  10.         &CFRelease,  
  11.         NULL,  
  12.     };  
  13.     //定义一个观察者  
  14.     static CFRunLoopObserverRef defaultModeObserver;  
  15.     //创建观察者  
  16.     defaultModeObserver = CFRunLoopObserverCreate(NULL, kCFRunLoopBeforeWaiting, YES, NSIntegerMax, &Callback, &context);  
  17.     //添加当前runloop的观察者  
  18.     CFRunLoopAddObserver(runloop, defaultModeObserver, kCFRunLoopDefaultMode);  
  19.     //释放  
  20.     CFRelease(defaultModeObserver);  
  21.       
  22.   
  23. }  
当绘制cell上的img的时候,添加一个任务task。

[objc] view plain copy
  1. -(void)addTask:(RunloopBlock)unit withKey:(id)key{  
  2.       
  3.     [self.tasks addObject:unit];  
  4.     [self.tasksKeys addObject:key];  
  5.   
  6.    //保证之前没有显示出来的任务。不再浪费时间加载  
  7.     if (self.tasks.count > self.maxQueueLength ) {  
  8.         [self.tasks removeObjectAtIndex:0];  
  9.         [self.tasksKeys removeObjectAtIndex:0];  
  10.   
  11.     }  
  12.       
  13. }  

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

[objc] view plain copy
  1. _timer = [NSTimer scheduledTimerWithTimeInterval:0.001 target:self selector:@selector(timerMethod) userInfo:nil repeats:YES];  

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

[objc] view plain copy
  1. static void Callback(CFRunLoopObserverRef observer, CFRunLoopActivity activity, voidvoid *info){  
  2.   
  3.     ViewController *vc = (__bridge ViewController*)info;  
  4.     if (vc.tasks.count == 0) {  
  5.         return;  
  6.     }  
  7.     BOOL result = NO;  
  8.     while (result == NO && vc.tasks.count ) {  
  9.           
  10.         //取出任务  
  11.         RunloopBlock unit = vc.tasks.firstObject;  
  12.         //执行任务  
  13.          result = unit();  //YES.所以说只执行了一次。  
  14.         //干掉第一个任务  
  15.         [vc.tasks removeObjectAtIndex:0];  
  16.         //干掉标示  
  17.         [vc.tasksKeys removeObjectAtIndex:0];  
  18.           
  19.     }  
  20.       
  21. }  

在cell上的操作

[objc] view plain copy
  1. [self addTask:^BOOL{  
  2.       [ViewController addImg1WithCell:cell];  
  3.       return YES;  
  4.   } withKey:indexPath];  
  5.     
  6.   [self addTask:^BOOL{  
  7.       [ViewController addImg2WithCell:cell];  
  8.       return YES;  
  9.   } withKey:indexPath];  
  10.     
  11.   [self addTask:^BOOL{  
  12.       [ViewController addImg3WithCell:cell];  
  13.       return YES;  
  14.   } withKey:indexPath];