有人有使用 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];