5

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)。

4

1 回答 1

1
- (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request

好吧,这不是alloc, new, 或copy方法……</p>

...并且 CSURLCache 不会在任何地方保留对象,因此它不拥有它。

所以,你需要自动释放它。

当然,这意味着该对象注定要失败,除非有什么东西保留它。您的应用程序崩溃了,因为它在对象死亡后尝试使用该对象。

使用 Zombies 模板在 Instruments 下运行您的应用程序。查看应用程序崩溃的位置以及cachedResponseForRequest:调用时它在做什么。调用者需要拥有该对象,直到应用程序崩溃,然后释放它。

于 2010-01-29T01:16:55.223 回答