使用NSThread iPhone下载100张图像时崩溃

时间:2011-08-08 12:09:30

标签: iphone uiimage nsthread

我目前正在制作iPhone杂志应用程序,该应用程序从互联网下载其杂志内容。杂志页面采用图像格式,大约有120页。

这是我解决问题的方法。

- (void) downloadDergiPages {

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

NSArray *resourcePaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [resourcePaths objectAtIndex:0];
documentsDirectory = [documentsDirectory stringByAppendingPathComponent:@"Dergilerim"];
documentsDirectory = [documentsDirectory stringByAppendingPathComponent:indirilenSayi];


for (int i=1; i<=numberOfPages; i++) {

    NSString *url = [NSString stringWithFormat:@"%@getdergipage?dergikey=%@&page=%d", [RepositoryInfo getHostName], indirilenDergi, i];
    NSLog(@"%@", url);

    NSData *receivedData =  [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:url]];

    NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%d.png",i]];
    [receivedData writeToFile:path atomically:YES];
    [receivedData release];

    [self performSelectorOnMainThread:@selector(updateProgress:) withObject:[NSNumber numberWithInt:i] waitUntilDone:YES];
}


[self performSelectorOnMainThread:@selector(removePopupView) withObject:nil waitUntilDone:YES];
//[self removePopupView];

[pool release];
} 

尽管此代码片段在iPad应用程序中运行没有问题,但它会导致应用程序在第44次完成后崩溃  在iPhone下载页面。这是因为我从日志控制台了解内存问题。 我只想获取图像并逐个保存到磁盘。我将释放所有分配“receivedData”。 这段代码可能存在什么问题,如何使其工作?

提前谢谢..

2 个答案:

答案 0 :(得分:1)

使用ASIHTTPRequest API进行下载。

答案 1 :(得分:0)

您应该使用NSURLConnection

每次通过委托方法收到数据时,将数据块保存到磁盘: connection:didReceiveData: