8

所以我有子类NSURLCache,每次我调用loadHTMLFromString:它时都会调用storeCachedRequest:forRequest:then cachedResponseForRequest:。这是我所拥有的:

- (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request
{
    NSString *pathString = [[request URL] absoluteString];

    NSCachedURLResponse * response = [super cachedResponseForRequest:request];
    if (response != nil)
        return response;
    else {
        NSString* myString= @"testing";

        NSData* data=[myString dataUsingEncoding: NSASCIIStringEncoding ];

        //
        // Create the cacheable response
        //
        NSURLResponse *response =
        [[[NSURLResponse alloc]
          initWithURL:[request URL]
          MIMEType:[self mimeTypeForPath:pathString]
          expectedContentLength:[data length]
          textEncodingName:nil]
         autorelease];
        NSCachedURLResponse * cachedResponse =
        [[[NSCachedURLResponse alloc] initWithResponse:response data:data] autorelease];

        [self storeCachedResponse:cachedResponse forRequest:request] ;

        //NSLog(@"DEFAULT CACHE WITH URL %@", [[request URL] absoluteString]);
        return [super cachedResponseForRequest:request];
    }

    return nil;
}

- (void)storeCachedResponse:(NSCachedURLResponse *)cachedResponse forRequest:(NSURLRequest *)request
{
    [super storeCachedResponse:cachedResponse forRequest:request];

    NSLog(@"STORE CACHED RESPONSE WITH URL %@", [[request URL] absoluteString]);
}

问题是当我cachedResponseForRequest:在保存后立即调用时,响应始终为零。为什么是这样?

我有:

NSURLRequest * req = [NSURLRequest requestWithURL:[NSURL URLWithString:self.imageSource_]];
NSCachedURLResponse * response = [[NSURLCache sharedURLCache] cachedResponseForRequest:req];

if (response == nil)
    NSLog(@"RESPONSE IS NIL");
else {
    NSString* theString = [[NSString alloc] initWithData:response.data encoding:NSASCIIStringEncoding];
    NSLog(@"RESPONSE IS NOT NIL %@", theString);
}

它总是打印响应为零。url 字符串与 storeCachedResponse. 由于某种原因,它没有缓存。我已将缓存大小设置为一定大小。

4

2 回答 2

1

不是 100% 肯定,但我认为你需要使用NSURLResponse你返回的NSURLConnection而不是创建你自己的。我的怀疑是,如果你只是创建一个NSURLResponse它没有为缓存设置任何标题,因此NSURLCache假设它应该缓存这个特定的结果。

于 2012-01-20T03:56:57.713 回答
1

在选择要缓存的内容时,默认的 NSURLCache 似乎非常随机。您最好的选择可能是将其子类化并直接在 cachedResponseForRequest: 中处理您介意的文件的缓存,并将其余部分留给 super。

于 2012-11-26T07:21:34.410 回答