您的位置:首页 > 移动开发 > IOS开发

iOS 处理缓存的三种方法<6度XZ>

2015-07-23 15:40 417 查看
缓存处理是个相当头疼的事情,要根据需要综合应用不同的策略。总的来说有以下几种情况:

1.URL缓存,例如社交应用的帖子浏览,要在viewDidAppear:里面进行URL缓存。简单来说就是用NSURLCache类,首先在AppDelegate.m里面的

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions;方法里面创建一个NSURLCache的单例:

//设置内存缓存大小

NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024 diskCapacity:10 * 1024 * 1024 diskPath:nil];

[NSURLCache setSharedURLCache:URLCache];

然后的ViewController.m里面实现方法:

//网络缓存响应方法

- (IBAction)senderButton:(id)sender {

//天气Api接口
NSString* path = @"http://www.weather.com.cn/data/sk/101110101.html";
[self getByURL:path andCallBack:^(id obj) {

NSString *str = [[NSString alloc]initWithData:obj encoding:NSUTF8StringEncoding];
NSLog(@"=========================================================\n");
NSLog(@"post缓存测试:%@",str);
NSLog(@"=========================================================\n");
}];

}


//网络请求的内存缓存方法

-(void)getByURL:(NSString *)path andCallBack:(CallBack)callback{

NSString*  pathStr = [path  stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSURL *url = [NSURL URLWithString:pathStr];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setCachePolicy:NSURLRequestReloadRevalidatingCacheData];
NSCachedURLResponse* response = [[NSURLCache sharedURLCache] cachedResponseForRequest:request];

//判断是否有缓存
if (response != nil) {
NSLog(@"有缓存");
[request setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
}else{

NSLog(@"没有缓存");
}

//创建NSURLConnection
NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
callback(data);

}


2.文件缓存,例如用户信息等基本不会变化的信息保存在本地沙箱

//用户信息缓存用文件保存在沙箱

- (IBAction)userCache:(UIButton *)sender {

self.UserPath = [self saveFileToDocuments:@"http://www.weather.com.cn/data/sk/101020100.html"];
}


//保存文件到沙箱
- (NSString *)saveFileToDocuments:(NSString *)url
{
NSString *resultFilePath = @"";

NSString *destFilePath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:url]; // 加上url,组合成本地文件PATH
NSString *destFolderPath = [destFilePath stringByDeletingLastPathComponent];

// 判断路径文件夹是否存在不存在则创建
if (! [[NSFileManager defaultManager] fileExistsAtPath:destFolderPath]) {
NSLog(@"文件夹不存在,新建文件夹");
[[NSFileManager defaultManager] createDirectoryAtPath:destFolderPath withIntermediateDirectories:YES attributes:nil error:nil];
}

// 判断该文件是否已经下载过
if ([[NSFileManager defaultManager] fileExistsAtPath:destFilePath]) {
NSLog(@"文件已下载\n");
resultFilePath = destFilePath;
} else {

NSLog(@"没有缓存,请求数据\n");
NSData *userInfoData = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];

if ([userInfoData writeToFile:destFilePath atomically:YES]) {
resultFilePath = destFilePath;
}
}
NSData *userInfoData=[[NSFileManager defaultManager] contentsAtPath:resultFilePath];
NSString* str = [[NSString alloc]initWithData:userInfoData encoding:NSUTF8StringEncoding];

NSLog(@"=========================================================\n");
NSLog(@"user:%@",str);
NSLog(@"=========================================================\n");

return resultFilePath;
}


3.图片缓存是最重要的,费流量还占内存,所以推荐使用第三方SDWebImage

最简单的就是用这个方法:

[self.imageView sd_setImageWithURL:url completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
if (cacheType==SDImageCacheTypeNone) {

NSLog(@"没有缓存,从网络下载");

}else if (cacheType==SDImageCacheTypeDisk){

NSLog(@"有缓存,从磁盘读取");

}else{

NSLog(@"有缓存,从内存读取");
}

}];


想知道这个方法的内部机制请看这里。

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