【发布时间】:2016-06-17 01:32:56
【问题描述】:
我想将 NSArray 中的 UIImage 作为 PNG 保存到本地。但是,当我在 for 循环中使用 UIImagePNGRepresentation 时,即使已经有一个 @autoreleasepool,内存也会大大增加。
for (int i = 0; i < array.count; i++) {
@autoreleasepool {
NSDictionary *src = array[i];
NSString *localPath = [SPLDPath stringByAppendingPathComponent:@"realImg"];
NSFileManager *file = [NSFileManager defaultManager];
if (![file fileExistsAtPath:localPath]) {
[file createDirectoryAtPath:localPath withIntermediateDirectories:NO attributes:nil error:nil];
}
NSString *screenShotImg = [localPath stringByAppendingPathComponent:[NSString stringWithFormat:@"ScreenShot_%d.png", i]];
NSData *PNGData = UIImagePNGRepresentation(src[@"image"]);
[PNGData writeToFile:screenShotImg atomically:YES];
}
}
所以我尝试将 UIImage 转换为 CGImageRef 并使用 ImageIO 框架来保存图像。然后使用 CGImageRelease() 在每个循环中释放内存。
-(void)saveImage:(CGImageRef)image directory:(NSString*)directory filename:(NSString*)filename {
@autoreleasepool {
CFURLRef url = (__bridge CFURLRef)[NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@", directory, filename]];
CGImageDestinationRef destination = CGImageDestinationCreateWithURL(url, kUTTypePNG, 1, NULL);
CGImageDestinationAddImage(destination, image, nil);
if (!CGImageDestinationFinalize(destination))
NSLog(@"ERROR saving: %@", url);
CFRelease(destination);
CGImageRelease(image);
}
}
for (int i = 0; i < array.count; i++) {
NSDictionary *src = array[i];
NSString *localPath = [SPLDPath stringByAppendingPathComponent:@"realImg"];
NSFileManager *file = [NSFileManager defaultManager];
if (![file fileExistsAtPath:localPath]) {
[file createDirectoryAtPath:localPath withIntermediateDirectories:NO attributes:nil error:nil];
}
NSString *fileName = [NSString stringWithFormat: @"ScreenShot_%d.png", i];
CGImageRef cgRef=[src[@"image"] CGImage];
[self saveImage:(cgRef) directory:localPath filename:fileName];
} enter image description here 内存减少了,但是,发生了一个新问题。由于过度释放的内存,我的应用程序崩溃了。因为 UIImage 是通过 CGImageRelease() 释放的,但是 ARC 也尝试在 app 结束前向僵尸对象发送 delloc 消息。 如何释放 CGImageRef 但不与 ARC 碰撞?
【问题讨论】:
标签: ios objective-c memory-leaks uiimage cgimageref