首先我们先监听当前runloop。然后根据runloop的状态进行cell的绘制。
- - (void)addRunloopObserver{
- //获取当前的runloop
- CFRunLoopRef runloop = CFRunLoopGetCurrent();
- //定义一个上下文
- CFRunLoopObserverContext context = {
- 0,
- (__bridge voidvoid *)self,
- &CFRetain,
- &CFRelease,
- NULL,
- };
- //定义一个观察者
- static CFRunLoopObserverRef defaultModeObserver;
- //创建观察者
- defaultModeObserver = CFRunLoopObserverCreate(NULL, kCFRunLoopBeforeWaiting, YES, NSIntegerMax, &Callback, &context);
- //添加当前runloop的观察者
- CFRunLoopAddObserver(runloop, defaultModeObserver, kCFRunLoopDefaultMode);
- //释放
- CFRelease(defaultModeObserver);
- }
- -(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, voidvoid *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];