您的位置:首页 > 理论基础 > 计算机网络

如何在网络中加载TabelView的数据(手动实现)?

2016-08-01 08:25 363 查看

从网络中加载到tabelView中多个图片需要注意(手动实现)

/**
0.设置存放数据的可变字典(等于内存),设置存放是否执行子线程的可变字典,key值为图片的唯一标识 (链接)。
1.存放位置包括:内存(自定义字典),缓存(cache中)
2.判断内存中是否有数据,没有的话执行下一步
3.拼接沙盒路径,判断数据data是否存在,存在的话设置图片,同时放到内存字典中;数据不存在的话,下一步
4.加载图片,首先设置站位图片;判断线程是否存在,(从可变字典中取出正在执行的线程);operations等于nil,执行下一步
5.开启子线程,加载数据,如果数据不存在直接返回,存在的话 设置数据,存到内存,存到缓存;
6.回到主线程;调用该[tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];方法加载数据,解决cell的复用问题。
7.把子线程加载到队列中去,并把线程存放到可变字典中去。
8.示例代码如下
*/


UIImage *image = [self.images objectForKey:topic.icon];

if (image)
{
cell.imageView.image = image;
}else
{
//去沙盒中找
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
//文件名
NSString *fileName = [topic.icon lastPathComponent];

//拼接文件全路径
NSString *fullFile = [caches stringByAppendingPathComponent:fileName];

NSData *data = [NSData dataWithContentsOfFile:fullFile];

if(data)
{
UIImage *image = [UIImage imageWithData:data];

cell.imageView.image = image;
//往内存中存一份
[self.images setObject:image forKey:topic.icon];

}else
{
cell.imageView.image = [UIImage imageNamed:@"timo"];

NSBlockOperation *opo = self.operations[topic.icon];

if (opo == nil)
{
NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{

[NSThread sleepForTimeInterval:2.0];

NSURL *url = [NSURL URLWithString:topic.icon];

NSData *data = [NSData dataWithContentsOfURL:url];

if (data == nil)
{
return ;
}

UIImage *image = [UIImage imageWithData:data];

//写到内存里去
[self.images setObject:image forKey:topic.icon];

//写到沙盒中去
[data writeToFile:fullFile atomically:YES];

NSLog(@"%zd",indexPath.row);

[[NSOperationQueue mainQueue] addOperationWithBlock:^{

[tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];

}];
}];

[self.queue addOperation:op];

self.operations[topic.icon] = op;
}

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