NSURLCache内存大小为零

问题描述:

我在使用同步调用缓存NSURLConnection响应时遇到了问题。我在一个类中初始化缓存,然后在另一个类中使用它。请注意,缓存内存容量是如何初始化为100KB的,但之后会奇迹般地重置为零。NSURLCache内存大小为零

- (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 

我将 “%p” 和[NSURLCache sharedURLCache]添加到您的NSLog语句,以确保共享对象保持不变。然后,我会为+ [NSURLCache setSharedURLCache:]和 - [NSURLCache setMemoryCapacity:]添加断点以查看发生了什么。

我在使用网页浏览的应用中遇到了这个问题。出于某种原因,当webviews初始化他们零缓存,不知道为什么。在这样的应用程序中,我使用忽略对setMemoryCapacity的调用的NSURLCache子类:如果它们为零。

类似:

-(void)setMemoryCapacity:(NSUInteger)memCap 
{ 
    if (memCap == 0) 
     return; 
    [super setMemoryCapacity:memCap]; 
} 

这里有同样的问题。思想缓存根本不起作用。在设置了一个没有UIWebView的小型测试项目后,[NSURLCache sharedURLCache] memoryCapacity]返回预期的10000000而不是0.

幸运的是,缓存不会被清除,所有先前缓存的对象将保留。所以Dougs解决方案就像一个魅力!

顺便说一句:一旦网页视图显示大小将被设置为零。之后将其设置回10000000,显示Web视图不会再次将大小设置为零。