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