我正在使用图像选择器库来允许用户从他们的照片库中选择许多图像。它们作为一个数组返回PHAssets
。然后,我想将所有内容转换PHAssets
为UIImages
并将它们写入应用程序的存储空间。
目前,我正在遍历所有资产并requestImageForAsset
同步调用。我的问题是,当这个循环运行时,内存使用量会出现非常高的峰值(30 张图像,它会达到 130MB)。我想防止这种情况。
这是我的代码:
for(PHAsset *asset in self.assets) {
NSLog(@"started requesting image %i", i);
[[PHImageManager defaultManager] requestImageForAsset:asset targetSize:PHImageManagerMaximumSize contentMode:PHImageContentModeAspectFit options:[self imageRequestOptions] resultHandler:^(UIImage *image, NSDictionary *info) {
dispatch_async(dispatch_get_main_queue(), ^{
assetCount++;
NSError *error = [info objectForKey:PHImageErrorKey];
if (error) NSLog(@"Image request error: %@",error);
else {
NSString *imagePath = [appDelegate.docsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%i.png",i]];
NSData *imageData = UIImagePNGRepresentation(image);
if(imageData) {
[imageData writeToFile:imagePath atomically:YES];
[self.imagesArray addObject:imagePath];
}
else {
NSLog(@"Couldn't write image data to file.");
}
[self checkAddComplete];
NSLog(@"finished requesting image %i", i);
}
});
}];
i++;
}
根据日志,我看到首先调用所有“开始请求图像 x”,然后调用所有完成块(“完成请求图像 x”)。我认为这可能会导致内存问题。确保在释放这些资源并移动到下一次迭代之前调用每次迭代的完成块可能会减少内存密集型。我怎样才能做到这一点?