0

AppDelegate メソッドでキャッシュを作成します

NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:(10 * 1024 * 1024) diskCapacity:(100 * 1024 * 1024) diskPath:nil];
[NSURLCache setSharedURLCache:URLCache];

次の NSURLConnection クラスがあります

@implementation ImageDownloader {
    NSURLConnection *serverConnection;
    NSMutableData *imageData;
}

- (void)startDownloading
{
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.link] cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:10];
    imageData = [NSMutableData new];
    serverConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
    [serverConnection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
    [serverConnection start];
}

- (void)cancelDownloading
{
    [serverConnection cancel];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [imageData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    UIImage *image = [[UIImage alloc] initWithData:imageData];
    [self sendDelegateImage:image];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    [self sendDelegateImage:nil];
}

- (void)sendDelegateImage:(UIImage *)image
{
    [self.delegate imageDownloader:self didLoadAtIndexPath:self.indexPath image:image];
}

@end

tableView セルが表示されたときに使用します。最初のロードではすべて問題なく、キャッシュの最初の使用ではすべて問題ありませんでしたが、3 回目に tableView をロードすると、キャッシュ データが非常に小さく返され、画像がありません。NSURLConnection が不正なキャッシュ データを返すのはなぜですか?

4

1 に答える 1

2

実装してみることができますconnection:didReceiveResponse:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
    {
        self.dataReceived = [[NSMutableData alloc] init];
    }

ドキュメントから:

まれに、ロード データのコンテンツ タイプが multipart/x-mixed-replace である HTTP ロードの場合など、デリゲートは複数の connection:didReceiveResponse: メッセージを受け取ります。これが発生した場合、デリゲートは、connection:didReceiveData: によって以前に配信されたすべてのデータを破棄する必要があり、新しく報告された URL 応答によって報告された、異なる可能性のある MIME タイプを処理できるように準備する必要があります。

[NSMutableData new]編集:また、データの初期化に使用していることに気付きました。を使用する必要があります[NSMutableData alloc] init]

于 2013-09-05T16:01:56.153 に答える