如何在从Document Directory iOS写入和读取图像期间处理内存警告

时间:2014-09-22 08:24:53

标签: ios objective-c iphone uiimage nsdocumentdirectory

我正在使用以下代码进行阅读和阅读在文档目录中编写代码,我的问题是,当下载大尺寸图像时,应用程序会给出内存警告并导致移植崩溃,以便如何处理。

- (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];
    }

}

1 个答案:

答案 0 :(得分:0)

使用SDWebImage t是图像缓存的最佳库...你可以从下面的url(Github)中选择它 https://github.com/rs/SDWebImage()

...一样 //这里我们使用新提供的setImageWithURL:方法来加载Web图像 [cell.imageView setImageWithURL:[NSURL URLWithString:@“http://www.domain.com/path/to/image.jpg”]                placeholderImage:[UIImage imageNamed:@“placeholder.png”]                       完成:^(UIImage *图像,NSError *错误,SDImageCacheType cacheType){...此处完成代码...}];