实现NSURLRequest,NSURLConnection和NSURLRequestReturnCacheDataElseLoad策略

时间:2011-01-21 21:43:01

标签: iphone cocoa nsurlconnection nsurlrequest

是否有人使用NSURLRequest,NSURLConnection和NSURLRequestReturnCacheDataElseLoad政策获得实施图像缓存的示例代码?

我正在使用以下代码,但似乎没有发生缓存。我一直从URL获取图像。请告诉我这里有什么问题:

NSMutableURLRequest *req=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://i54.tinypic.com/10pd2jk.png"]];
    NSData *data=[NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil];
    NSLog(@"Received %d bytes", [data length]);
    [req setCachePolicy:NSURLRequestReturnCacheDataElseLoad];
    data=[NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil];
    NSLog(@"Received %d bytes", [data length]);
    [[NSURLCache sharedURLCache] setMemoryCapacity:1024*1024*10];


    UIImage *myImage = [UIImage imageWithData:data];
    UIImageView *sd = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 50, 50)];
    sd.image = myImage;
    [self.view addSubview:sd];

2 个答案:

答案 0 :(得分:5)

您可能需要查看使用SDURLCache:https://github.com/rs/SDURLCache

SDURLCache实际上将缓存保存到磁盘,而NSURLCache则没有。 NSURLCache仅在内存中缓存,因此在您的应用会话中。请参阅ReadMe链接,该链接更详细地解释了它。

更新:从iOS 5.x开始,NSURLCache看起来像是缓存到磁盘:http://petersteinberger.com/blog/2012/nsurlcache-uses-a-disk-cache-as-of-ios5/

答案 1 :(得分:0)