我们正在为我们公司开发一个企业应用程序。该应用程序应该脱机工作,这意味着我们需要将超过10K的产品图像下载到iPad。每个图像可以从几KB到4M。这样做起初我们使用以下代码下载图像:
-(BOOL)DownloadFileInBatch :(NSArray*) fileArr
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [paths objectAtIndex:0];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
queue.maxConcurrentOperationCount = 4;
NSBlockOperation *completionOperation = [NSBlockOperation blockOperationWithBlock:^{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[[NSNotificationCenter defaultCenter] postNotificationName:@"taskDone" object:self];
}];
}];
@autoreleasepool
{
NSBlockOperation *operation;
for(int i = 0; i < fileArr.count; i++)
{
operation = [NSBlockOperation blockOperationWithBlock:^{
NSURL *url = [[NSURL alloc] initWithString:[[fileArr objectAtIndex:i] objectForKey:@"image_url"]];
NSData *data = [NSData dataWithContentsOfURL:url];
NSString *filename = [documentDirectory stringByAppendingString:[NSString stringWithFormat:@"/%@", [url lastPathComponent]]];
NSLog(@"downloading file : %@ : no : %d", [documentDirectory stringByAppendingString:[NSString stringWithFormat:@"/%@", [url lastPathComponent]]], i);
BOOL success = [data writeToFile:filename atomically:YES];
if(!success)
{
// failed to download
}
}];
[completionOperation addDependency:operation];
}
}
[queue addOperations:completionOperation.dependencies waitUntilFinished:NO];
[queue addOperation:completionOperation];
return YES;
}
但是当我们使用这段代码下载时,应用程序因内存问题而崩溃。(甚至把@autoreleasepool解决了崩溃问题)。似乎逐个下载(甚至4个图像并行)不适合这个数据量,因为它会导致我们内存问题。我只想知道从服务器下载这些数量的图像的最佳方法是什么到iPad?
提前致谢...