iOS中如何优化Cell中图片的下载性能

来源:互联网 发布:卓越淘宝工具箱下载 编辑:程序博客网 时间:2024/06/06 20:02

在iOS开发中使用最为常见的是UITableView,其中UITabelViewCell中下载图片,会影响用户下拉刷新UI,导致卡顿,用户体验不好,在这篇blog中,我将以一个例子来说明如何优化UITableView下载图片
1.使用懒加载方式,首先将CellData数据加载进来
// lazy
- (NSMutableArray*)apps {
if (!_apps) {
NSString *path = [[NSBundle mainBundle]pathForResource:@”apps.plist” ofType:nil];
NSArray *dictArray = [NSArray arrayWithContentsOfFile:path];

    NSMutableArray *appArray = [NSMutableArray array];    for (NSDictionary *dict in dictArray) {        App *app = [App appWithDict:dict];        [appArray addObject:app];    }    _apps = appArray;}return _apps;

}

2.然后在UITaleView的dataSource方法中加载数据
//Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.apps.count;
}
- (UITableViewCell )tableView:(UITableView )tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *ID = @”app”;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID forIndexPath:indexPath];

if (!cell) {    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];}App *app = self.apps[indexPath.row];cell.textLabel.text = app.name;cell.detailTextLabel.text = app.download;UIImage *image = self.images[app.icon];if (image) {    cell.imageView.image = image;} else {    cell.imageView.image = [UIImage imageNamed:@"placeholder"];    // 下载图片    [self download:app.icon indexPath:indexPath];}return cell;

}

(1)其中在加载图片过程中首先判断图片是否已经下载过,如果下载过直接加载,如果没有下载过那么就需要下载,并且需要填写一个默认的图片
其中判断图片是否已经下载过是使用字典查询的
- (NSMutableDictionary *)images {
if (!_images) {
_images = [[NSMutableDictionary alloc]init];
}
return _images;
}
下载图片,是需要创建一个线程来执行下载,首先应该判断是否下载线程已经执行,如果执行,不需要重复下载,因此这个线程也是与一个imageURL来绑定

  • (void)download:(NSString )imageUrl indexPath:(NSIndexPath )indexPath {
    NSBlockOperation *operation = self.operations[imageUrl];
    // 如果存在操作则直接返回,防止已经在下载的操作重复下载
    if (operation) {
    return;
    }
    __weak typeof (self) appsVc = self;
    operation = [NSBlockOperation blockOperationWithBlock:^{
    NSURL *url = [NSURL URLWithString:imageUrl];
    NSData *data = [NSData dataWithContentsOfURL:url];
    UIImage *image = [UIImage imageWithData:data];

    [[NSOperationQueue mainQueue] addOperationWithBlock:^{    if (image) {        appsVc.images[imageUrl] = image;    }    [appsVc.operations removeObjectForKey:imageUrl];    [appsVc.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];}];

    }];
    [self.queue addOperation:operation];

    self.operations[imageUrl] = operation;

}
为进一步优化,应在用户滑动过程中停止下载,结束拖拽时候开始下载
/**
* 当用户开始拖拽表格时调用
*/
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
// 暂停下载
[self.queue setSuspended:YES];
}

/**
* 当用户停止拖拽表格时调用
*/
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
// 恢复下载
[self.queue setSuspended:NO];
}

1 0
原创粉丝点击