我在使用同步调用缓存NSURLConnection响应时遇到问题。我在一个类中初始化缓存,然后在另一个类中使用它。注意缓存容量是如何被初始化为100KB的,但随后又被神奇地重置为零。
- (id)init {
if (self = [super init]) {
// Creates a custom URL cache that uses both memory and disk.
NSURLCache *sharedCache =
[[NSURLCache alloc] initWithMemoryCapacity:kMemoryCacheSize * 1000000
diskCapacity:kDiskCacheSize * 1000000
diskPath:diskPath];
[NSURLCache setSharedURLCache:sharedCache];
NSLog(@"Cache memory capacity = %d bytes", [[NSURLCache sharedURLCache] memoryCapacity]);
NSLog(@"Cache disk capacity = %d bytes", [[NSURLCache sharedURLCache] diskCapacity]);
//[sharedCache release];
}
return self;
}
// NSLOG OUTPUT:
// [6842:20b] Cache memory capacity = 100000 bytes
// [6842:20b] Cache disk capacity = 20000000 bytes在另一节课上。
NSLog(@"Cache memory capacity = %d bytes", [[NSURLCache sharedURLCache] memoryCapacity]);
NSLog(@"Cache disk capacity = %d bytes", [[NSURLCache sharedURLCache] diskCapacity]);
NSLog(@"Cache Memory Usage = %d bytes", [[NSURLCache sharedURLCache] currentMemoryUsage]);
NSLog(@"Cache Disc Usage = %d bytes", [[NSURLCache sharedURLCache] currentDiskUsage]);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:objectURL cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:20];
data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(@"Image Request finished. Error = %@",[error localizedDescription]);
NSLog(@"Cache size after = %d bytes", [[NSURLCache sharedURLCache] currentMemoryUsage]);
// NSLog Output:
// Cache memory capacity = 0 bytes
// Cache Disc Usage = 0 bytes
// Cache Memory Usage = 0 bytes
// Cache disk capacity = 20000000 bytes
// Image Request finished. Error = (null)
// Cache size after = 0 bytes发布于 2010-10-03 07:26:10
我在带有webviews的应用程序中遇到过这个问题。由于某些原因,当webviews初始化时,他们清零缓存,不确定为什么。在这样的应用程序中,我使用了一个忽略对setMemoryCapacity的调用的NSURLCache子类:如果它们为零。
类似于:
-(void)setMemoryCapacity:(NSUInteger)memCap
{
if (memCap == 0)
return;
[super setMemoryCapacity:memCap];
}发布于 2010-01-28 17:06:01
我会将"%p“和NSURLCache sharedURLCache添加到NSLog语句中,以确保共享对象保持不变。然后,我将为+NSURLCache setSharedURLCache:和-NSURLCache setMemoryCapacity:添加断点,以查看发生了什么。
发布于 2011-05-26 20:54:17
在这里也有同样的问题。认为缓存根本不起作用。在设置了一个没有UIWebView的小型测试项目后,NSURLCache sharedURLCache memoryCapacity]返回预期的10000000而不是0。
幸运的是,缓存不会被清除,所有以前缓存的对象都将保留。因此,Dougs的解决方案就像是一种魔力!
顺便说一句:一旦显示了网页视图,大小将被设置为零。将其设置为10000000之后,显示web视图将不会再次将大小设置为零。
https://stackoverflow.com/questions/2153268
复制相似问题