前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >iOS 处理缓存的三种方法

iOS 处理缓存的三种方法

作者头像
王大锤
发布2018-05-17 12:10:10
8750
发布2018-05-17 12:10:10
举报
文章被收录于专栏:王大锤王大锤王大锤

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

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的去这里下载

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2014-11-24 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档