【发布时间】:2017-02-20 00:16:20
【问题描述】:
我正在尝试下载一些图像(从 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 包装代码,但没有任何区别。
【问题讨论】:
-
尝试使用@autoreleasepool 包装您的代码,如下所示:stackoverflow.com/a/9779032/1689376
-
@alex 我已经尝试过了,但没有成功。相应地更新了我的问题。
标签: ios objective-c memory-leaks uiimagepngrepresentation