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 提交雷达后,这似乎是一个已知问题(雷达 #7640470)。
最佳答案
- (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request
好吧,这不是alloc
、new
或copy
方法……
... 并且 CSURLCache 不会在任何地方保留该对象,因此它不拥有它。
所以,你需要自动释放它。
当然,这意味着该对象注定要失败,除非有什么东西保留它。您的应用程序崩溃是因为它在对象死亡后尝试使用该对象。
使用 Zombies 模板在 Instruments 下运行您的应用程序。查看应用崩溃的位置以及调用 cachedResponseForRequest:
时它正在做什么。调用者需要拥有该对象,直到应用程序崩溃为止,然后释放它。
关于objective-c - NSURLCache 与自动释放的对象一起崩溃,但在其他情况下会泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2159205/