NSURLCache内存大小为零 [英] NSURLCache Memory Size is zero

查看:144
本文介绍了NSURLCache内存大小为零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用同步调用缓存NSURLConnection响应时遇到麻烦.我在一类中初始化缓存,然后在另一类中使用它.请注意,如何将缓存容量初始化为100KB,然后在以后神奇地将其重置为零.

I am having trouble caching NSURLConnection responses using a synchronous call. I initialize the cache in one class and then use it in another. Notice how the cache memory capacity gets initialized to 100KB but then is magically reset to zero later.

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

推荐答案

我在具有网络视图的应用程序中遇到了这个问题.出于某种原因,当Web视图初始化时,它们会将缓存归零,但不知道为什么.在此类应用中,我使用NSURLCache子类忽略对setMemoryCapacity的调用:如果它们为零.

I've had this problem in apps with webviews. For some reason when webviews initialize they zero the cache, not sure why. In apps like this I use a NSURLCache subclass that ignore calls to setMemoryCapacity: if they are zero.

类似:

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

这篇关于NSURLCache内存大小为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆