【发布时间】:2011-01-21 21:43:00
【问题描述】:
谁有使用 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];
【问题讨论】:
-
我也有同样的问题。 SDURLCache 似乎是要走的路,但文档中提供的示例代码 sn-p 理想情况下会更完整。我也没有观察到任何缓存。当我加载视图时,我说的是 [self getImage];我假设通过使用 SDURLCache,我不需要做任何其他事情。还是我需要手动保留“最后修改”时间,然后从共享缓存中读取?如果是这样,这不会节省我的时间,因为我最终会以手动方式实现缓存。
标签: iphone cocoa nsurlconnection nsurlrequest