[英]How to handle memory warning during write and read image from Document Directory iOS
I am using below code for reading & writing code in document directory , my problem is that when there is large size images downloaded then application gives memory warning and crash immigiate so how to handle this. 我正在使用下面的代码在文档目录中读写代码,我的问题是当下载大尺寸图像时,应用程序会发出内存警告并崩溃崩溃,因此如何处理。
- (void)cacheImage:(UIImage *)image forRequest:(NSURLRequest *)request
{
NSData *data=UIImageJPEGRepresentation(image, 1.0);
[self writeImageData:data forPlayListID:[self cachedFileNameForKey:request.URL.absoluteString]];
}
-(UIImage *)getImageFromForPlayListID:(NSString *)strID{
NSString *docDirPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
docDirPath = [docDirPath stringByAppendingPathComponent:@"/MyFolder"];
NSString *filePathCellImg = [NSString stringWithFormat:@"%@/%@",docDirPath,strID];
NSData *data=[NSData dataWithContentsOfFile:filePathCellImg];
UIImage *musicImage = [UIImage imageWithData:data];
return musicImage;
}
-(void)writeImageData:(NSData *)imageData forPlayListID:(NSString *)strID{
NSError *error;
NSString *docDirPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *dataPath = [docDirPath stringByAppendingPathComponent:@"/MyFolder"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
// [[NSFileManager defaultManager] removeItemAtPath:dataPath error:&error];
NSString *filePathCellImg = [NSString stringWithFormat:@"%@/%@",dataPath,strID];
[imageData writeToFile:filePathCellImg atomically:NO];
if (![[NSFileManager defaultManager] fileExistsAtPath:filePathCellImg]) {
[[NSFileManager defaultManager] createFileAtPath:filePathCellImg
contents:imageData
attributes:nil];
}
}
Use SDWebImage t is best library for image caching...you can Pick it from below url(Github) https://github.com/rs/SDWebImage() 使用SDWebImage t是用于图像缓存的最佳库...您可以从url(Github) https://github.com/rs/SDWebImage()下面选择它
Like... // Here we use the new provided setImageWithURL: method to load the web image [cell.imageView setImageWithURL:[NSURL URLWithString:@" http://www.domain.com/path/to/image.jpg "] placeholderImage:[UIImage imageNamed:@"placeholder.png"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {... completion code here ...}]; 就像... // //在这里,我们使用新提供的setImageWithURL:方法来加载网络图像[cell.imageView setImageWithURL:[NSURL URLWithString:@“ http://www.domain.com/path/to/image.jpg ” ] placeholderImage:[UIImage imageNamed:@“ placeholder.png”]已完成:^(UIImage * image,NSError * error,SDImageCacheType cacheType){...这里的完成代码...}];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.