2014-03-27 41 views
0

我试图从服务器上下载数千张图片(每个最大350 Kb),但是我收到了超过一千张图像,我收到警报“Memory Presure”。内存压力下载许多图像

基本上我有与图像的所有名字的数组,并做一个循环,使一对一这样的:

for (int x=0; x<unique.count; x++) { 

    NSURL *ImageLink = [NSURL URLWithString:[NSString stringWithFormat:@"http://urltoimagesfolder.com/", [unique objectAtIndex:x]]]; 
    NSData *data = [NSData dataWithContentsOfURL:ImageLink]; 
    UIImage *img = [[UIImage alloc] initWithData:data]; 

    if (data.length !=0) { 

    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[unique objectAtIndex:x]]; //add our image to the path 

    [UIImageJPEGRepresentation(img, 1.0) writeToFile:fullPath atomically:YES]; 

    //[self saveImage:img :NombreFoto]; 
    //[self Miniatura:img :[NSString stringWithFormat:@"mini-%@", [unique objectAtIndex:x]]]; 
    } 

    data = nil; 
    img = nil; 


} 

问:我怎样才能下载的所有图像,而无需与应用程序崩溃内存压力?

+0

你的问题是什么? – rocky

+0

编辑如何在没有应用程序崩溃和内存压力的情况下下载所有图像? –

+0

嗯......写完后释放img? – rocky

回答

0

UIImageJPEGRepresentation()可能导致内存溢出。 但是您不需要使用该功能,您可以检查接收到的数据是否为图像,并通过发送消息writeToFile:data对象将其字节直接写入磁盘。

您可以修复你这样的代码:

for (int x=0; x<unique.count; x++) { 
    NSURL *ImageLink = [NSURL URLWithString:[NSString stringWithFormat:@"http://urltoimagesfolder.com/", [unique objectAtIndex:x]]]; 
    NSData *data = [NSData dataWithContentsOfURL:ImageLink]; 
    if (data.length !=0) { 

     UIImage *img = [[UIImage alloc] initWithData:data]; 
     if (img) { 
      NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[unique objectAtIndex:x]]; //add our image to the path 
      [data writeToFile:fullPath atomically:YES]; 
     } 
     img = nil; 

    } 
    data = nil; 
} 

然而,这并不是最佳的解决方案。 -dataWithContentsOfURL:是同步方法,将在下载文件时停止执行主线程。因此,UI会在下载过程中挂起。为了不让你的UI挂起,你可以使用异步URL请求。

请参阅-sendAsynchronousRequest:queue:completionHandler:NSURLConnection类的方法。或者,如果您的应用仅适用于iOS 7,请参阅-dataTaskWithURL:completionHandler: