我无法使用同步调用缓存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
答案 0 :(得分:4)
我在使用网页浏览的应用中遇到了这个问题。出于某种原因,当webviews初始化时,它们将缓存归零,不确定原因。在像这样的应用程序中,我使用NSURLCache子类忽略对setMemoryCapacity的调用:如果它们为零。
类似的东西:
-(void)setMemoryCapacity:(NSUInteger)memCap
{
if (memCap == 0)
return;
[super setMemoryCapacity:memCap];
}
答案 1 :(得分:1)
我会将“%p”和[NSURLCache sharedURLCache]添加到NSLog语句中,以确保共享对象保持不变。然后我会为+ [NSURLCache setSharedURLCache:]和 - [NSURLCache setMemoryCapacity:]添加断点以查看发生了什么。
答案 2 :(得分:0)
这里有同样的问题。思想缓存根本不起作用。在没有UIWebView的情况下设置一个小测试项目后,[NSURLCache sharedURLCache] memoryCapacity]返回预期的10000000而不是0。
幸运的是,缓存不会被清除,所有以前缓存的对象都将保留。所以Dougs解决方案就像一个魅力!
BTW:一旦显示Web视图,大小将设置为零。之后将其设置回10000000,显示Web视图不会再将大小设置为零。