Runloop加载大图
来源:互联网 发布:java是后端吗 编辑:程序博客网 时间:2024/05/21 09:07
首先我们先监听当前runloop。然后根据runloop的状态进行cell的绘制。
- - (void)addRunloopObserver{
-
-
- CFRunLoopRef runloop = CFRunLoopGetCurrent();
-
- CFRunLoopObserverContext context = {
- 0,
- (__bridge voidvoid *)self,
- &CFRetain,
- &CFRelease,
- NULL,
- };
-
- static CFRunLoopObserverRef defaultModeObserver;
-
- defaultModeObserver = CFRunLoopObserverCreate(NULL, kCFRunLoopBeforeWaiting, YES, NSIntegerMax, &Callback, &context);
-
- 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, 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();
-
- [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];