RunLoop UITableViewCell加载高清大图的速度优化

来源:互联网 发布:linux web服务器 编辑:程序博客网 时间:2024/04/30 10:10

RunLoop UITableViewCell加载高清大图的速度优化

2017-02-14 14:25 出处:清屏网 人气:73 评论(0

iOS开发中,UITableView的优化一直是一个老生常谈的问题,除了常用的预加载,缓存等方法以外,其实利用RunLoop 的循环也可以实现超清大图的流畅加载,具体的使用方法我们利用一个demo来详细理解:

首先,我们有一个需求,就是要从网络加载高清大图到UITableViewCell上,而且每个Cell上面加载多张图片,当cell数量过多的时候,我们需要保持流畅度和加载速度。

那么我们做一个简单的分析:

1,因为这里用到了Runloop循环,那么我们可以监听到runloop的每次循环,在每一次循环当中我们考虑去进行一次图片下载和布局。2,既然要在每次循环执行一次任务,我们可以先把所有图片加载的任务代码块添加到一个数组当中,每次循环取出第一个任务进行执行。*3,因为runloop在闲置的时候会自动休眠,所以我们要想办法让runloop始终处于循环中的状态。

好的,那么我们就可以开始考虑代码实现:

第一步,先把uitableview基本效果实现

@property (strong,nonatomic) UITableView* showImageTableView;//懒加载-(UITableView *)showImageTableView{    if (!_showImageTableView) {        _showImageTableView = [[UITableView alloc]initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];        _showImageTableView.backgroundColor = [UIColor yellowColor];        _showImageTableView.delegate = self;        _showImageTableView.dataSource = self;    }    return _showImageTableView;}//注册    [self.showImageTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:ShowImageTableViewReusableIdentifier];//添加    [self.view addSubview:self.showImageTableView];//数据源代理#pragma mark- UITableViewDelegate-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:ShowImageTableViewReusableIdentifier];    //每个cell中添加3张图片    for (int i = 0; i < 3; i++)    {       #这里是添加图片的方法    }    return cell;}-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{    return 399;}-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{    return 135;}

第二步,初始化可变数组用来存储任务(代码块)

typedef void(^SaveFuncBlock)();//存放任务的数组@property (nonatomic, strong) NSMutableArray *saveTaskMarr;//最大任务数(超过最大任务数的任务就停止执行)@property (nonatomic, assign) NSInteger maxTasksNumber;//任务执行的代码块@property (nonatomic, copy) SaveFuncBlock saveFuncBlock;-(NSMutableArray *)saveTaskMarr{    if (!_saveTaskMarr) {        _saveTaskMarr = [NSMutableArray array];    }    return _saveTaskMarr;}    self.maxTasksNumber = 18;

第三步,新建cell添加图片的方法

-(void)addImageToCell:(UITableViewCell*)cell andTag:(NSInteger)tag{    UIImageView* cellImageView = [[UIImageView alloc]initWithFrame:CGRectMake(tag*(ImageWidth+5), 5, ImageWidth, ImageHeight)];    dispatch_async(dispatch_get_global_queue(0,0), ^{        NSData* imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://img5.duitang.com/uploads/item/201312/14/20131214173346_iVKdT.jpeg"]];        dispatch_async(dispatch_get_main_queue(), ^{            cellImageView.image = [UIImage imageWithData:imageData];            [cell.contentView addSubview:cellImageView];        });    });}

第四步,将任务添加到数组保存

//添加任务进数组保存-(void)addTasks:(SaveFuncBlock)taskBlock{    [self.saveTaskMarr addObject:taskBlock];    //超过每次最多执行的任务数就移出当前数组    if (self.saveTaskMarr.count > self.maxTasksNumber) {        [self.saveTaskMarr removeObjectAtIndex:0];    }}

第五步,在cellForRow方法当中,添加方法:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:ShowImageTableViewReusableIdentifier];    for (int i = 0; i < 3; i++)    {        //添加任务到数组        __weak typeof(self) weakSelf = self;        [self addTasks:^{            //下载图片的任务            [weakSelf addImageToCell:cell andTag:i];        }];    }    return cell;}

第六步,监听RunLoop

//注册监听    [self addRunloopObserver];//这里面都是C语言 -- 添加一个监听者-(void)addRunloopObserver{    //获取当前的RunLoop    CFRunLoopRef runloop = CFRunLoopGetCurrent();    //定义一个centext    CFRunLoopObserverContext context = {        0,        ( __bridge void *)(self),        &CFRetain,        &CFRelease,        NULL    };    //定义一个观察者    static CFRunLoopObserverRef defaultModeObsever;    //创建观察者    defaultModeObsever = CFRunLoopObserverCreate(NULL,                                                 kCFRunLoopBeforeWaiting,                                                 YES,                                                 NSIntegerMax - 999,                                                 &Callback,                                                 &context                                                 );    //添加当前RunLoop的观察者    CFRunLoopAddObserver(runloop, defaultModeObsever, kCFRunLoopDefaultMode);    //c语言有creat 就需要release    CFRelease(defaultModeObsever);}

第七步,也是最关键的步骤,使用定时器,保持RunLoop循环中。

//定时器,保证runloop一直处于循环中@property (nonatomic, weak) NSTimer *timer;self.timer = [NSTimer scheduledTimerWithTimeInterval:0.001 target:self selector:@selector(setRunLoop) userInfo:nil repeats:YES];//此方法主要是利用计时器事件保持runloop处于循环中,不用做任何处理-(void)setRunLoop{}

最后一步,在runLoop循环中去处理事件

//MARK: 回调函数//定义一个回调函数  一次RunLoop来一次static void Callback(CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info){    ViewController * vcSelf = (__bridge ViewController *)(info);    if (vcSelf.saveTaskMarr.count > 0) {        //获取一次数组里面的任务并执行        SaveFuncBlock funcBlock = vcSelf.saveTaskMarr.firstObject;        funcBlock();        [vcSelf.saveTaskMarr removeObjectAtIndex:0];    }}

好啦。到此为止,我们想要的效果就基本出来了,大家可以去试试:hushed:,同样的道理也可以应用于其他场景。

0 0
原创粉丝点击