[英]Memory pressure downloading many images
我正在嘗試從服務器下載數千張圖片(每張最大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;
}
問題:如何在應用程序不因內存不足而崩潰的情況下下載所有圖像?
UIImageJPEGRepresentation()
可能會導致內存溢出。 但是您不需要使用該功能,可以檢查接收到的數據是否為圖像,並通過向data
對象發送消息writeToFile:
將其字節直接寫入磁盤。
您可以這樣修改代碼:
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:作為替代。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.