gpt4 book ai didi

ios - Objective-c UIImagePNGRepresentation 导致内存泄漏

转载 作者:行者123 更新时间:2023-11-29 00:38:47 24 4
gpt4 key购买 nike

我正在尝试下载一些图像(从 base64 字符串转换为 UIImage)并将其保存到设备,但不断收到内存警告。

ontracFullScreenImageViewController *etrackDiagrams = ((ontracFullScreenImageViewController*)[viewControllerDictionary objectForKey:@"E-track Diagrams"]);
NSMutableSet *etrackSet = [[NSMutableSet alloc] init];

for (UIImage *image in etrackDiagrams.imageArray) {


NSAutoreleasePool *localPool = [[NSAutoreleasePool alloc] init];
//convert the image to NSData and store it in the documents directory
NSData *pngData = UIImagePNGRepresentation(image);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory
NSString * timeInMS = [NSString stringWithFormat:@"%lld", [@(floor([[NSDate date] timeIntervalSince1970] * 1000)) longLongValue]];
NSString *filePath = [documentsPath stringByAppendingPathComponent:[ NSString stringWithFormat:@"%@_%@_etrack_diagram_%i_%i_image.png", delegate.userName, timeInMS, self.dataObject.dataPack.pack_id, [etrackDiagrams.imageViewArray indexOfObject:image]]]; //Add the file name
[pngData writeToFile:filePath atomically:YES];
NSLog(@"filepath %@", filePath);
NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
if ([currSysVer isEqualToString:@"5.0.1"]) {
[[NSURL URLWithString:filePath] setResourceValue: [NSNumber numberWithBool: YES] forKey: NSURLIsExcludedFromBackupKey error: &error];
}
//Add the file Path to ImageLinks
[etrackDiagrams.imageLinks addObject:filePath];
//save the image location in Core Data
EtrackDiagram *etrackDiagram = [NSEntityDescription
insertNewObjectForEntityForName:@"EtrackDiagram"
inManagedObjectContext:context];
etrackDiagram.locationString = filePath;
etrackDiagram.dataObject = dataObject;
[etrackSet addObject:etrackDiagram];
[dataObject addEtrackDiagramsObject:etrackDiagram];
[localPool drain];

}
[dataObject addEtrackDiagrams: etrackSet];

内存警告发生在 NSData *pngData = UIImagePNGRepresentation(image); 处,因为图像非常大。

不幸的是,我无法控制图像的大小,但需要一种方法将它们保存到设备上,以便稍后在图库中使用它们。

我尝试用 @autoreleasepool 包装代码,但没有什么区别。

最佳答案

真正的问题是这一行:

for (UIImage *image in etrackDiagrams.imageArray) {

这意味着您在内存中保存了一组图像。那总是很危险的。您需要将所有这些图像保存在磁盘上并一次将它们加载到内存中(并且以非缓存方式)。您的目标应该是一次最多在内存中保存一张图像。

关于ios - Objective-c UIImagePNGRepresentation 导致内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39977524/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com