How to manage NSUserdefaults values for image and textview?
Iam developing one applciation.In that application i used the both imageview and textview.And iam used the NSUserdefaults for storing the imageview image value and textview text value.But when iam going to another page and 开发者_Go百科coming to main page only imageview image data will be available in nsuserdefaults,textview text data is not avialable.So please tell me how to get the textview text data also by using nsuserdefaults
You should check your Key for spelling mistakes. By the way, just for reference,
Methods of saving images to NSUserDefaults:
Number 1: Saving and retrieving image directly:
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSData *imageData = [NSKeyedArchiver archivedDataWithRootObject:imageView.image];
[userDefaults setObject:imageData forKey:@"Image"];
//Retrieving
UIImage *image = (UIImage*)[NSKeyedUnarchiver unarchiveObjectWithData:[userDefaults objectForKey:@"Image"]];
Number 2: Saving the image in documents directory and saving its path in 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]];
Method of saving text to NSUserDefaults:
//Saving
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setValue:textView.text forKey:@"Text"];
//Retrieving
textView.text = [userDefaults valueForKey:@"Text"];
精彩评论