CSURLCache
旨在缓存资源以供离线浏览,因为NSURLCache
仅将数据存储在内存中。
如果cachedResponse
在返回应用程序崩溃之前自动释放,如果没有,则对象只是泄漏。
任何可以阐明这一点的光都将不胜感激。
请注意stringByEncodingURLEntities
是一个分类方法NSString
。
@interface CSURLCache : NSURLCache {} @end
@implementation CSURLCache
- (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request
{
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[[[request URL] absoluteString] stringByEncodingURLEntities]];
if ([[NSFileManager defaultManager] fileExistsAtPath:path])
{
NSData *data = [[NSData alloc] initWithContentsOfFile:path];
NSURLResponse *response = [[NSURLResponse alloc] initWithURL:[request URL]
MIMEType:nil
expectedContentLength:[data length]
textEncodingName:nil];
NSCachedURLResponse *cachedResponse = [[NSCachedURLResponse alloc] initWithResponse:response
data:data];
[response release];
[data release];
return cachedResponse;
}
return nil;
}
@end
更新:向 Apple 提交雷达后,这似乎是一个已知问题 (Radar #7640470)。