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

cell 网络数据缓存

2016-02-27 00:00 781 查看
摘要: 缓存 cache:为了提高数据加载速度。
计算机存储器结构(低到高):磁盘-内存-cache-寄存器->cpu。
网络:云端-磁盘-内存-cache-寄存器->cpu。
从左到右访问数据:访问速度⬆️,存储空间⬇️

0.数据存储结构:
缓存 cache:为了提高数据加载速度。
计算机存储器结构(低到高):磁盘-内存-cache-寄存器->cpu。
网络:云端网络-磁盘-内存-cache-寄存器->cpu。
从左到右访问数据:访问速度⬆️,存储空间⬇️

1.网络存储器-->内存
1.1,网络数据异步下载,更新UI.数据从网络到达内存中。
gcd这样:

dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSURL *url = [NSURL URLWithString:urlStr];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [UIImage imageWithData:data];
dispatch_async(dispatch_get_main_queue(), ^{
cell.imageView.image = img;
});
});

1.2.或者NSOperation这样

NSOperationQueue *queue = [[NSOperationQueue alloc]init];
NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
NSURL *url = [NSURL URLWithString:urlStr];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [UIImage imageWithData:data];
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
cell.imageView.image = img;
}];
}];
[queue addOperation:operation];


2.添加内存索引
2.1.添加图片数据索引:
因为单纯的下载数据,导致反复刷新tableView的时候,又会下载 data。
所以使用 dictory记录,(key = url,value=image)。
每当 赋值image的时候从 dic中查找。
2.2.添加线程索引:
进行中的线程,还没有把数据下载完。所以使用 dict记录下载线程,(key = url,value=operation)
每当要开启线程的时候,先从 dict中查找线程。

3.内存——沙盒
3.1.下载完成后,更新UI,将image写入沙盒(文件名是url最后的一段,为了是和服务器中文件名一致)

- (void) writeDataToSandBox:(NSString *)urlStr withData:(NSData *)data
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *imgFileName = [urlStr lastPathComponent];
NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *path = [cachesPath stringByAppendingString:@"/icon/"];

if (![fileManager fileExistsAtPath:path]) {
[fileManager createDirectoryAtPath:path withIntermediateDirectories:YES
attributes:NULL error:NULL];
}
NSString *fullPath = [path stringByAppendingString:imgFileName];
[data writeToFile:fullPath atomically:YES];
}

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