iphone - NSURLCache 内存大小为零

标签 iphone caching nsurlconnection nsurlcache

我在使用同步调用缓存 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

在另一个类(class)...

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

最佳答案

我在带有 WebView 的应用程序中遇到了这个问题。由于某种原因,当 webview 初始化时,它们会将缓存归零,不知道为什么。在这样的应用程序中,我使用 NSURLCache 子类,该子类会忽略对 setMemoryCapacity: 的调用(如果它们为零)。

类似于:

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

关于iphone - NSURLCache 内存大小为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2153268/

相关文章:

iPhone - 如何部分隐藏 subview ?

caching - Mutt 缓存大小限制 header 和消息

angular - 通过 Angular 6 Service Worker 中的新鲜度缓存 Assets

iOS : Internet connection is available but getting time out error in web service call , 相同的网络服务在 android 中运行

ios - 在 El Capitan beta 5 上提交应用程序时 xCode 崩溃

iphone - ASIHTTPRequest 中 POST 中的空主体

swift - NSURLErrorDomain 代码 = -1002 尽管转义了受限字符

ios - 优化 iOS 中的多个异步图片下载

android - Admob 如何确定文本上下文以显示有针对性的广告?

java - Infinispan - 根据实体 expiration.lifespan 设置