您的位置:首页 > 其它

多线程实现多图片下载1

2016-03-27 14:54 141 查看
展示效果如下:

#pragma mark - 数据源方法
- (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];

DDZApp *app = self.apps[indexPath.row];

cell.textLabel.text = app.name;
cell.detailTextLabel.text = app.download;

//先从内存中取出图片
UIImage *image = self.imgCache[app.icon];
if (image) {
cell.imageView.image = image;
}else {
//内存中没有图片

//将图片文件数据写入到沙盒中
NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
//获得文件名
NSString *filename = [app.icon lastPathComponent];
//计算出文件的全路径
NSString *file = [cachesPath stringByAppendingPathComponent:filename];
//加载沙盒的文件数据
NSData *data = [NSData dataWithContentsOfFile:file];

//判断沙盒中是否有图片
if (data) {
//直接加载沙盒中图片
cell.imageView.image = [UIImage imageWithData:data];
//存到字典(内存)中
self.imgCache[app.icon] = cell.imageView.image;

}else {
//下载图片
data = [NSData dataWithContentsOfURL:[NSURL URLWithString:app.icon]];

cell.imageView.image = [UIImage imageWithData:data];
//存到内存中
self.imgCache[app.icon] = cell.imageView.image;

//将图片数据写入到沙盒中
[data writeToFile:file atomically:YES];
}

}
return cell;
}


View Code
这两个方法是UITableView必须要实现的方法

第一个是返回数据量,没什么好说的

第二个是绑定数据

具体的流程看下图

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: