如何管理图像和textview的NSUserdefaults值?

时间:2011-07-29 05:28:26

标签: iphone

我开发了一个applciation.In该应用程序我使用了imageview和textview.And我使用NSUserdefaults来存储imageview图像值和textview文本值。但是当我去另一个页面并进入主页面时只有imageview图像数据将在nsuserdefaults中提供,textview文本数据不可用。所以请告诉我如何使用nsuserdefaults获取textview文本数据

1 个答案:

答案 0 :(得分:2)

您应该检查您的密钥是否存在拼写错误。顺便说一句,仅供参考,

将图像保存到NSUserDefaults的方法:

编号1:直接保存和检索图像:

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSData *imageData = [NSKeyedArchiver archivedDataWithRootObject:imageView.image];
[userDefaults setObject:imageData forKey:@"Image"];

//Retrieving
UIImage *image = (UIImage*)[NSKeyedUnarchiver unarchiveObjectWithData:[userDefaults objectForKey:@"Image"]];

编号2:将图像保存在文档目录中并在NSUserDefaults中保存其路径:

//Saving
//Obtain the path for Documents Directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];      

//Append Image name to the path
NSString *imagePath = [[documentsDirectory stringByAppendingPathComponent:@"Image"] retain];  

//Creating a file at this path
NSFileManager *fileManager = [NSFileManager defaultManager]; 
BOOL ok = [fileManager createFileAtPath:dataFilePath contents:nil attributes:nil];
if (!ok) {
    NSLog(@"Error creating file %@", dataFilePath);
} 
else {
    //Writing image to the created file
    NSFileHandle *myFileHandle = [NSFileHandle fileHandleForWritingAtPath:imagePath];

    [myFileHandle writeData:UIImageJPEGRepresentation(imageView.image, 1.0)];
    [myFileHandle closeFile];
}

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
if (userDefaults) {

    [userDefaults setObject:imagePath forKey:@"ImagePath"];

}

//Retrieving
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSString *imagePath = [userDefaults objectForKey:@"ImagePath"];
NSFileHandle* fileHandle = [NSFileHandle fileHandleForReadingAtPath:dataFilePath];
UIImage* loadedImage = [UIImage imageWithData:[fileHandle readDataToEndOfFile]];

将文本保存到NSUserDefaults的方法:

//Saving
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setValue:textView.text forKey:@"Text"];

//Retrieving
textView.text = [userDefaults valueForKey:@"Text"];