2012-07-24 90 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];