【发布时间】:2011-01-10 16:19:13
【问题描述】:
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)。
【问题讨论】:
-
如果它们没有自动发布,你确定它们会被泄露吗?你确定你的程序崩溃是因为你试图释放它们吗?内存管理规则明确规定您将负责释放该对象。
-
是的,如果不自动发布,它们肯定会泄漏。程序崩溃,因为保留消息被发送到一个释放的对象
标签: objective-c cocoa autorelease nsurlcache