2013-09-05 31 views
0

在我的AppDelegate方法創建緩存NSURLConnection的返回壞cacheData

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細胞出現時。在第一次加載的時候一切都很好,並且在第一次使用緩存的時候都很好,但是當我第三次加載我的tableView的時候,緩存數據返回的很小,而且我沒有圖像。爲什麼NSURLConnection返回錯誤的緩存數據?

回答

2

你可以嘗試實施connection:didReceiveResponse:

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

從文檔:

在極少數情況下,例如在HTTP負載情況下的負載數據的 內容類型是多/ x-mixed-replace, 委託將收到多個連接:didReceiveResponse: 消息。如果發生這種情況,代表應丟棄先前通過連接didReceiveData提供的所有數據 ,並應該準備好 以處理新報告的URL響應報告的可能不同的MIME類型。

編輯: 此外,只注意到你正在使用[NSMutableData new]初始化數據;你應該使用[NSMutableData alloc] init]