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 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"];
Related
How can I store NSMutableArray of custom objects?
I have this code for loading and saving files:
- (NSMutableArray *)loadDataFromFile:(NSString *)fileName {
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
NSString *path = [docDir stringByAppendingPathComponent:fileName];
NSFileManager *fileMgr = [NSFileManager defaultManager];
if (![fileMgr fileExistsAtPath:path]) {
NSArray *fileArray = [fileName componentsSeparatedByString:#"."];
NSString *name = [fileArray objectAtIndex:0];
NSString *ext = [fileArray objectAtIndex:1];
NSString *bundle = [[NSBundle mainBundle] pathForResource:name ofType:ext];
[fileMgr copyItemAtPath:bundle toPath:path error:&error];
}
NSMutableArray *data = [[NSMutableArray alloc] initWithContentsOfFile:path];
return data;
}
- (void)saveData:(NSMutableArray *)arrayData toFile:(NSString *)filename forKey:(NSString *)key {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
NSString *path = [docDir stringByAppendingPathComponent:filename];
[arrayData writeToFile: path atomically:YES];
NSLog(#"%#", arrayData);
}
But when I used data.plist as filename, it didn't work because NSLog(#"%#", arrayData); returns list custom object adresses:
"AreaTableRecord: 0x76a7ef0"
This custom object is inserted to array using this code:
AreaTableRecord *area=[[AreaTableRecord alloc] init];
area.title=title;
area.lastScore=0;
area.vocabulary=[[NSMutableArray alloc] init];
[self.areas addObject:area];
How could I store NSMutableArray self.areas that contains custom objects AreaTableRecord?
and
What file format shloud I use to store this data? (it seems to me that plist is not working in this case)
You are only able to store primitive data types in NSDefaults or a plist. In order to work around this you can either choose to store your information in a database....or encode your objects as byte streams and then save them into a file.
Take a look at this thread. It details how to go about encoding your objects.
Basically you need to add these methods to your custom class:
- (void)encodeWithCoder:(NSCoder *)encoder
{
//Encode properties, other class variables, etc
[encoder encodeObject:self.question forKey:#\"question\"];
[encoder encodeObject:self.categoryName forKey:#\"category\"];
[encoder encodeObject:self.subCategoryName forKey:#\"subcategory\"];
}
- (id)initWithCoder:(NSCoder *)decoder
{
self = [super init];
if( self != nil )
{
//decode properties, other class vars
self.question = [decoder decodeObjectForKey:#\"question\"];
self.categoryName = [decoder decodeObjectForKey:#\"category\"];
self.subCategoryName = [decoder decodeObjectForKey:#\"subcategory\"];
}
return self;
}
And then in order to use them you make calls as such:
For setting:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *myEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:obj];
[defaults setObject:myEncodedObject forKey:#\"myEncodedObjectKey\"];
For retrieving:
NSUserDefaults defaults = [NSUserDefaults standardUserDefaults];
NSData *myEncodedObject = [defaults objectForKey: key];
MyCustomObject* obj = (MyCustomObject*)[NSKeyedUnarchiver unarchiveObjectWithData: myEncodedObject];
I want to create different folders for each user's account. There are images of user's that are need to be stored in their folder. How can i achieve that i am getting no idea.Can anyone help me.
Thanks in advance.
Create directory in your app like this:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *folderPath = [documentsDirectory stringByAppendingPathComponent:#"UniqueUserAccount"];
if (![[NSFileManager defaultManager] fileExistsAtPath:folderPath])
[[NSFileManager defaultManager] createDirectoryAtPath:folderPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder
Now saving NSMutableArray refer read-and-write-array-dictionary-and-other-collections-to-files link.
folderPath = [folderPath stringByAppendingPathComponent:#"array.out"];
[yourArray writeToFile:folderPath atomically:YES];
Read array like this:
NSArray *arrayFromFile = [NSArray arrayWithContentsOfFile:folderPath];
NSLog(#"%#",arrayFromFile);
EDIT : To save image in user account folder from array of images
for(int i = 0;i < [arrImages count];i++)
{
folderPath = [folderPath stringByAppendingPathComponent:[NSString stringWithFormat:#"Images%d",i]]; //here folder Path with Image file
//Our goal is to create UIImage into NSData if u have image in bundle then take like this:
NSMutableString *imgPath;
imgPath=[[NSMutableString alloc] initWithString: [[NSBundle mainBundle] resourcePath]]; //get bundle path
[imgPath stringByAppendingPathComponent:[arrImages objectAtIndex:i]]; //get image from bundle to write
NSData *imageData = [NSData dataWithContentsOfFile:imgPath]; //create nsdata of image
//if u have UIImage
NSData *imageData = UIImagePNGRepresentation([arrImages objectAtIndex:i]) //image reference here to convert into data
[imageData writeToFile:folderPath atomically:YES]; //write here
}
you can create directory in your app by:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *newFolder = [(NSString*)[paths objectAtIndex:0] stringByAppendingPathComponent:#"uniqueIdentifierForAccount"];
if (![[NSFileManager defaultManager] fileExistsAtPath:newFolder]) {
[[NSFileManager defaultManager] createDirectoryAtPath:newFolder withIntermediateDirectories:YES attributes:nil error:nil];
}
It sounds to me that rather than needing actual folders, you really just need to store an array connected to a name. I would advise using the NSUserDefaults. You can achieve this functionality like this:
//instantiate the NSUserDefaults
NSUserDefaults *storage = [NSUserDefaults standardUserDefaults];
NSArray *userArray;
NSString *username;
//Then to store:
[storage setObject:userArray forKey:username];
//and to recall:
userArray = [storage objectForKey:username];
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I wanted to save an image that has been taken to the application documents directory, but for some reason, the counter always going up but there are no picture inside the directory. what seems to be the problem?
Thanks alot!
- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info
{
[picker dismissModalViewControllerAnimated:YES];
self.imageViewRecipt.image = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
//
// Getting the current counter value
//
NSUserDefaults * prefs = [NSUserDefaults standardUserDefaults];
int imageCounter;
imageCounter = [[prefs objectForKey:#"imageCounter"]intValue];
//
// Obtaining saving path
//
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"image%i.png",imageCounter]];
//
// Extracting image from the picker and saving it
//
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:#"public.image"])
{
UIImage *editedImage = [info objectForKey:UIImagePickerControllerEditedImage];
NSData *webData = UIImagePNGRepresentation(editedImage);
[webData writeToFile:imagePath atomically:YES];
//
// Saving the new counter into the plist
//
imageCounter++;
[prefs setInteger:imageCounter forKey:#"imageCounter"];
[prefs synchronize];
}
}
OK, so I fixed it by removing the "mediaType" and the if statment and replace it with this:
- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info
{
[picker dismissModalViewControllerAnimated:YES];
self.imageViewRecipt.image = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
//
// Getting the current counter value
//
NSUserDefaults * prefs = [NSUserDefaults standardUserDefaults];
int imageCounter;
imageCounter = [[prefs objectForKey:#"imageCounter"]intValue];
//
// Obtaining saving path
//
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"image%i.png",imageCounter]];
//
// Extracting image from the picker and saving it
//
UIImage *editedImage = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
NSData *webData = UIImagePNGRepresentation(editedImage);
[webData writeToFile:imagePath atomically:YES];
NSData *webData = UIImagePNGRepresentation(editedImage);
[webData writeToFile:imagePath atomically:YES];
//
// Saving the new counter into the plist
//
imageCounter++;
[prefs setInteger:imageCounter forKey:#"imageCounter"];
[prefs synchronize];
}
and now it's working just fine.
In UserDefault file I have six fields. I want to persist two field always and reset four other field in some scenario. What is best approach to handle this?
If your want the four field to reset with their default values.
And the default value may be an empty string ,
#define KDefault #""
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
if (standardUserDefaults)
{
[standardUserDefaults setObject:KDefault forKey:#"first"];
[standardUserDefaults setObject:KDefault forKey:#"two"];
[standardUserDefaults setObject:KDefault forKey:#"third"];
[standardUserDefaults setObject:KDefault forKey:#"four"];
[standardUserDefaults synchronize];
}
Edited:
For removing field rather than resetting: Use the below
[standardUserDefaults removeObjectForKey:#"first"];
[standardUserDefaults removeObjectForKey:#"two"];
[standardUserDefaults removeObjectForKey:#"third"];
[standardUserDefaults removeObjectForKey:#"four"];
[standardUserDefaults synchronize];
.you can use NSFileManager..sample code
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //1
NSString *documentsDirectory = [paths objectAtIndex:0]; //2
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"user.plist"]; //3
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path]) //4
{
NSString *bundle = [[NSBundle mainBundle] pathForResource:#"user" ofType:#"plist"]; //5
[fileManager copyItemAtPath:bundle toPath: path error:&error]; //6
}
NSMutableDictionary *savedStock = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
//load from savedStock example int value
NSString* userName;
NSString* password;
NSString* pin;
userName = [savedStock objectForKey:#"name"];
password = [savedStock objectForKey:#"password"];
if([userName isEqualToString:#"some"] && [userName isEqualToString:#"some"] && [pin isEqualToString:#"some"])
{
[self setAdd];
}
else
{
[self pinAdd];
}
How do I save an NSString as a .txt file on my apps local documents directory (UTF-8)?
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents directory
NSError *error;
BOOL succeed = [myString writeToFile:[documentsDirectory stringByAppendingPathComponent:#"myfile.txt"]
atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (!succeed){
// Handle error here
}
Something like this:
NSString *homeDirectory;
homeDirectory = NSHomeDirectory(); // Get app's home directory - you could check for a folder here too.
BOOL isWriteable = [[NSFileManager defaultManager] isWritableFileAtPath: homeDirectory]; //Check file path is writealbe
// You can now add a file name to your path and the create the initial empty file
[[NSFileManager defaultManager] createFileAtPath:newFilePath contents:nil attributes:nil];
// Then as a you have an NSString you could simple use the writeFile: method
NSString *yourStringOfData;
[yourStringOfData writeToFile: newFilePath atomically: YES];
He is how to save NSString into Documents folder. Saving other types of data can be also realized that way.
- (void)saveStringToDocuments:(NSString *)stringToSave {
NSString *documentsFolder = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *fileName = [NSString stringWithString:#"savedString.txt"];
NSString *path = [documentsFolder stringByAppendingPathComponent:fileName];
[[NSFileManager defaultManager] createFileAtPath:path contents:[stringToSave dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];
}
you could use NSUserDefaults
Saving:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:#"TextToSave" forKey:#"keyToLookupString"];
Reading:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *myString = [prefs stringForKey:#"keyToLookupString"];
I was using this method to save some base64 encoded image data to the disk. When opening the text file on my computer I kept having trouble reading the data because of some line breaks and returns being added automatically.
The following code fixes this issue:
myString = [myString stringByReplacingOccurrencesOfString:#"\n" withString:#""];
myString = [myString stringByReplacingOccurrencesOfString:#"\r" withString:#""];
// write string to disk