2012-07-24 57 views
1

我有一个非常头痛的工作,我的应用程序出了什么问题。我正在尝试保存并加载UIImages,对吗?似乎不是这样。保存和加载UIImage iPhone问题

我有一个类与这些方法来保存,加载和删除一个唯一的字符串的图像。我喜欢它,很好,很简单。这里是类:

imageSavedLoad.h:

#import <Foundation/Foundation.h> 

@interface imageSaveLoad : NSObject 

- (void)saveImage:(UIImage*)image forKey:(NSString*)imageName; 
- (void)removeImage:(NSString*)fileName; 
- (UIImage*)loadImage:(NSString*)imageName; 

@end 

imageSaveLoad.m:

#import "imageSaveLoad.h" 


@implementation imageSaveLoad 

//saving an image 
- (void)saveImage:(UIImage*)image forKey:(NSString*)imageName 
{ 
    NSData *imageData = UIImagePNGRepresentation(image); 
    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", imageName]]; 
    [fileManager createFileAtPath:fullPath contents:imageData attributes:nil]; 
    NSLog(@"image saved"); 
} 

//removing an image 
- (void)removeImage:(NSString*)fileName 
{ 
    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", fileName]]; 
    [fileManager removeItemAtPath: fullPath error:NULL]; 
    NSLog(@"image removed"); 
} 

//loading an image 
- (UIImage*)loadImage:(NSString*)imageName 
{ 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", imageName]]; 
    return [UIImage imageWithContentsOfFile:fullPath]; 
} 

@end 

,我想保存,加载或删除图像导入我的班:#import "imageSaveLoad.h"

然后我创建它的一个实例并调用所需的方法(这里我保存):

imageSaveLoad *imgSL = [[imageSaveLoad alloc] init]; 
[imgSL saveImage:photoImgView.image forKey:@"yourPhoto"]; 

然后在另一个视图/类,我想检索图像:

imageSaveLoad *imgSL = [[imageSaveLoad alloc] init]; 
yourImgView.image = [imgSL loadImage:@"yourPhoto"]; 

yourImgView什么也不显示的空白。

那么我哪里错了?我检查了所有IBOutlet连接,并且所有代码都被调用。我正在使用的方法有问题吗?

任何帮助非常感谢,它驱使我在墙上。

+1

请登录以下针对我们所在的完整路径您保存了'UIImage'中,加载路径,你想从中加载'UIImage',并且请确保在保存之后检查:是否是Documents文件夹中的图像文件? – holex 2012-07-24 15:59:25

+0

您应该提供一个错误并查看[fileManager createFileAtPath:fullPath contents:imageData attributes:nil]的返回码; - 你只是假设成功。假设Documents目录现在是用于iCloud的,并且您可能需要为此目的使用缓存目录。 – 2012-07-24 16:16:55

+0

这些方法可以是类方法。只是在说' – 2012-07-24 16:58:58

回答

0

当保存图像,通过替换这一行试试:

[fileManager createFileAtPath:fullPath contents:imageData attributes:nil]; 

随着

[imageData writeToFile:fullpath atomically:YES];