1 为什么要优化大图加载
大图片在渲染的时候,比较耗费时间
我们利用RUNLOOP 来优化:
思路:1.每一次RUNLOOP,都只加载一个小任物,把图片任务放到数组,从数组循环来加载.这样可以是项目达到流畅.
2.只加载当前视图内的图片任务
3.为了不让runloop休眠.我们要用一个timer区持有这个runloop 或者 通知注册runloop事件,让快要睡眠的时候去执行唤醒.
直接贴代码
#import "DWURunLoopWorkDistribution.h"
#import <objc/runtime.h>
#define DWURunLoopWorkDistribution_DEBUG 1
@interface DWURunLoopWorkDistribution ()
@property (nonatomic, strong) NSMutableArray *tasks;
@property (nonatomic, strong) NSMutableArray *tasksKeys;
@property (nonatomic, strong) NSTimer *timer;
@end
@implementation DWURunLoopWorkDistribution
- (void)removeAllTasks {
[self.tasks removeAllObjects];
[self.tasksKeys removeAllObjects];
}
- (void)addTask:(DWURunLoopWorkDistributionUnit)unit withKey:(id)key{
//将任务对应的添加到task 和 taskkeys数组数组中方便在注册方法中的callback中以待处理
[self.tasks addObject:unit];
[self.tasksKeys addObject:key];
// NSLog(@"%@%@",unit,key);
if (self.tasks.count > self.maximumQueueLength) {
[self.tasks removeObjectAtIndex:0];
[self.tasksKeys removeObjectAtIndex:0];
}
}
- (void)_timerFiredMethod:(NSTimer *)timer {
//We do nothing here
}
- (instancetype)init
{
if ((self = [super init])) {
_maximumQueueLength = 30;
_tasks = [NSMutableArray array];
_tasksKeys = [NSMutableArray array];
// _timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(_timerF