I want to save the content of TextFields in plist with corresponding Key-Values pair.
Like Password field should be saved with the Key-Password and Value-(entered in textField).
How can I do that?
and want to access it in some other class. Can I do it? If yes, then how?
Adding Stuff into plist is easy. Full working code follows which adds a persons contact info into a plist -
// get paths from root direcory
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
// get documents path
NSString *documentsPath = [paths objectAtIndex:0];
// get the path to our Data/plist file
NSString *plistPath = [documentsPath stringByAppendingPathComponent:#"Data.plist"];
// set the variables to the values in the text fields
self.personName = nameEntered.text;
self.phoneNumbers = [[NSMutableArray alloc] initWithCapacity:3];
[phoneNumbers addObject:homePhone.text];
[phoneNumbers addObject:workPhone.text];
[phoneNumbers addObject:cellPhone.text];
// create dictionary with values in UITextFields
NSDictionary *plistDict = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects: personName, phoneNumbers, nil] forKeys:[NSArray arrayWithObjects: #"Name", #"Phones", nil]];
NSString *error = nil;
// create NSData from dictionary
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
// check is plistData exists
if(plistData)
{
// write plistData to our Data.plist file
[plistData writeToFile:plistPath atomically:YES];
}
else
{
NSLog(#"Error in saveData: %#", error);
[error release];
}
[source]
You can save the content of textField to Plist in the following manner :
NSMutableDictionary *_plistDict = [NSMutableDictionary dictionaryWithContentsOfFile:pListPath];
[_plistDict setValue:textField.text forKey:#"Password"];
[_plistDict writeToFile:pListPath atomically:YES];
If you want to retrieve that value from pList , You can use the following code :
NSMutableDictionary *_plistDict = [NSMutableDictionary dictionaryWithContentsOfFile:pListPath];
NSString *status = [NSString stringWithFormat:#"%#",[_plistDict objectForKey:#"Password"]];
Yes, Take a NSMutableDictionary add values of UITextFeild property of text in in keys of Dictionary. Like
NSMutableDicitonary * dictionary = [[NSMutableDictionary alloc] init];
[dictionary setObject:textfield.text forKey:#"username"];
[dictionary setObject:textfield.text forKey:#"password"];
Save Dictionary in plist and use it where ever it requires.
NSString *aDocumentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *aFilePath = [NSString stringWithFormat:#"%#/plistName.plist", aDocumentsDirectory];
NSMutableArray *plistArray = [[NSMutableArray alloc] initWithContentsOfFile:aFilePath];
NSMutableDictionary *newComment = [NSMutableDictionary dictionary];
[newComment setValue:userName.text forKey:#"username"];
[newComment setValue:password.text forKey:#"password"];
[plistArray addObject:newComment];
[plistArray writeToFile:filePath atomically:YES];
Best practice would be saving these info in NSUserDefaults instead of a plist. NSUserDefautls can be accessed from anywhere in your project.
Saving:
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:[yourTextfield text] forKey:#"password"];
Retrieving:
NSString *myPassword = [[NSUserDefaults standardUserDefaults] objectForKey:#"password"];
Related
Below is my method to save data:
self.doctorString = #"Doctor Bob";
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *plistPath = [documentsPath stringByAppendingPathComponent:#"doctorprofile.plist"];
NSDictionary *plistDict = [[NSDictionary alloc] initWithObjects: [NSArray arrayWithObjects: self.doctorString, nil] forKeys:[NSArray arrayWithObjects: #"DoctorName", nil]];
NSError *error = nil;
NSData *plistData = [NSPropertyListSerialization dataWithPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 options:0 error:&error];
if(plistData){
[plistDict writeToFile:plistPath atomically:YES];
NSLog(#"Data saved successfully");
NSLog(#"Error : %#",error);
}else{
NSLog(#"Data not happily saved");
}
My plist structure as below:-
It returns Data saved successfully message but when I checked on the plist file, it is not saved there.
As per my reading of the code given, it will only write the key for DoctorName with the value of Doctor Bob. There is no error in the code itself. You can check the return value of writeToFile method as per below.
BOOL ret = [plistDict writeToFile:plistPath atomically:YES];
if the return value is YES the data is written to .plist file.
I am trying to add data to plist but I could not, let's tell you what I am doing:
Have a look to my plist:
Lets see my code, I created 2 arrays:
#property NSMutableArray *nameArr;
#property NSMutableArray *countryArr;
Here is the code where I save the data:
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *plistPath = [documentsPath stringByAppendingPathComponent:#"Data.plist"];
[self.nameArr addObject:self.theName.text];
[self.countryArr addObject:self.cellPhone.text];
NSDictionary *plistDict = [[NSDictionary alloc] initWithObjects: [NSArray arrayWithObjects: self.nameArr, self.countryArr, nil] forKeys:[NSArray arrayWithObjects: #"city", #"state", nil]];
NSString *error = nil;
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
if(plistData)
{
[plistData writeToFile:plistPath atomically:YES];
NSLog(#"Data Saved");
}
else
{
NSLog(#"Data not saved");
}
The below image shows the error, the app terminate but I do not know where is the problem.
Probably the array properties are declared but never initialized.
You have to add
nameArr = [[NSMutableArray alloc] init];
countryArr = [[NSMutableArray alloc] init];
somewhere before using them.
Regarding the warning use the method suggested by the compiler.
I have a code to get the data of a plist file and a code to write data to a plist file. Now the things is, that it add's the readed data in one array (See images).
I want it in different arrays (See green image)
HERE IS MY CODE:
- (void)WriteData {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"MuziekList.plist"];
if ([fileManager fileExistsAtPath:path] == NO) {
NSString *resourcePath = [[NSBundle mainBundle] pathForResource:#"MuziekList" ofType:#"plist"];
[fileManager copyItemAtPath:resourcePath toPath:path error:&error];
}
//_______________________________________________________________________________________________________________
NSMutableDictionary *savedStock = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
//load from savedStock example int value
NSArray *NummerTexts;
NummerTexts = [savedStock objectForKey:#"Nummers"];
NSString *NummerTextsR = [[NummerTexts valueForKey:#"description"] componentsJoinedByString:#" - "];
NSArray *ArtiestTexts;
ArtiestTexts = [savedStock objectForKey:#"Artiesten"];
NSString *ArtiestTextsR = [[ArtiestTexts valueForKey:#"description"] componentsJoinedByString:#" - "];
//_______________________________________________________________________________________________________________
NSUserDefaults *CurrentVideoNummerResult = [NSUserDefaults standardUserDefaults];
NSString *CurrentVideoNummer = [CurrentVideoNummerResult stringForKey:#"CurrentVideoNummer"];
NSUserDefaults *CurrentVideoArtiestResult = [NSUserDefaults standardUserDefaults];
NSString *CurrentVideoArtiest = [CurrentVideoArtiestResult stringForKey:#"CurrentVideoArtiest"];
/*
NSUserDefaults *CurrentVideoIDResult = [NSUserDefaults standardUserDefaults];
NSString *CurrentVideoID = [CurrentVideoIDResult stringForKey:#"CurrentVideoID"];
*/
NSMutableDictionary *plist = [[NSDictionary dictionaryWithContentsOfFile:path] mutableCopy];
NSMutableArray *newArray = [[NSMutableArray alloc] init];
NSMutableArray *newArray2 = [[NSMutableArray alloc] init];
newArray = [NSMutableArray arrayWithObjects:CurrentVideoNummer, NummerTextsR, nil];
[plist setObject:newArray forKey:#"Nummers"];
newArray2 = [NSMutableArray arrayWithObjects:CurrentVideoArtiest, ArtiestTextsR, nil];
[plist setObject:newArray2 forKey:#"Artiesten"];
[plist writeToFile:path atomically:YES];
}
Click link for images
https://www.dropbox.com/sh/wrk8h8cnwye8myx/AADl4omkGdl3S4ESXv6NbymVa?dl=0
Your question and problem are confusing. Maybe this will help:
Your code reads your current array (NummerTexts), flattens that array to a single string (NummerTextsR), gets a second string (CurrentVideoNummer), then builds a two-element array (newArray).
Your question appears to be why do you get a two-element array...?
If you don't want to flatten your original array don't do so, just make a mutable copy of it, something like:
NSMutableArray *existingTexts = [[NummerTexts valueForKey:#"description"] mutableCopy];
add your new element:
[existingTexts addObject:currentVideoNummer];
and write it back like you already are.
HTH
BTW Do not start local variable names with an uppercase letter, this goes against convention and is why the syntax highlighting in your question is all wrong.
I have a code to add data to a plist file object whenever I save my data. they crush of earlier!
I would like them in addition to more! how is this possible?
my code to save my data:
// get paths from root direcory
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
// get documents path
NSString *documentsPath = [paths objectAtIndex:0];
// get the path to our Data/plist file
NSString *plistPath = [documentsPath stringByAppendingPathComponent:#"Data.plist"];
// set the variables to the values in the text fields
self.personName = nameEntered.text;
self.phoneNumbers = [[NSMutableArray alloc] initWithCapacity:3];
[phoneNumbers addObject:homePhone.text];
[phoneNumbers addObject:workPhone.text];
[phoneNumbers addObject:cellPhone.text];
// create dictionary with values in UITextFields
NSDictionary *plistDict = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects: personName, phoneNumbers, nil] forKeys:[NSArray arrayWithObjects: #"Name", #"Phones", nil]];
NSString *error = nil;
// create NSData from dictionary
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
// check is plistData exists
if(plistData)
{
// write plistData to our Data.plist file
[plistData writeToFile:plistPath atomically:YES];
}
else
{
NSLog(#"Error in saveData: %#", error);
[error release];
}
You are overwriting the plist file with new data each time. If you want to append then you need to load the existing data from the plist file first, then add your new data to that dictionary, then write out the updated dictionary.
Read the contents of the plistPath:
NSMutableData *myData = [NSMutableData dataWithContentsOfFile:plistPath];
And change this:
// create NSData from dictionary
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
to:
// create NSData from dictionary
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
[myData appdendData:plistData];
and finally write myData to file.
Hope that helps!
I'm using the below bit of code to add a new array into a plist, but each time I add a new array with the textfield in my app it overwrites the old one even though it has a brand new key.. any ideas?
- (IBAction)saveViewerItems
{
// get paths from root direcory
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
// get documents path
NSString *documentsPath = [paths objectAtIndex:0];
// get the path to our Data/plist file
NSString *plistPath = [documentsPath stringByAppendingPathComponent:#"Data.plist"];
// set the variables to the values in the text fields
self.data = [[NSMutableArray alloc] initWithCapacity:20];
// create dictionary with values in UITextFields
NSDictionary *plistDict = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects: data, nil] forKeys:[NSArray arrayWithObjects: (#"%#", text), nil]];
NSString *error = nil;
// create NSData from dictionary
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
// check is plistData exists
if(plistData)
{
// write plistData to our Data.plist file
[plistData writeToFile:plistPath atomically:YES];
}
}
In order to get the dictionaty already in the file, use:
NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithContentsOfFile:(NSString *)filePath];
In order to write another array in that dictionary (using a different key), use:
[dictionary setObject:(id)myArray forKey:(NSString *)myKey];
In order to write back to the file, use:
[dictionary writeToFile:(NSString *)filePath atomically:YES];
There is no need to use NSData class. For more info, check out Apple NSDictionary Class
Try this one
// get paths from root direcory
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
// get documents path
NSString *documentsPath = [paths objectAtIndex:0];
// get the path to our Data/plist file
NSString *plistPath = [documentsPath stringByAppendingPathComponent:#"Data.plist"];
NSMutableDictionary *plist = [[NSDictionary dictionaryWithContentsOfFile:plistPath] mutableCopy];
// set the variables to the values in the text fields
self.data = [[NSMutableArray alloc] initWithCapacity:20];
[plist setObject:[NSArray arrayWithObjects: data, nil] forKey:forKeys:[NSArray arrayWithObjects: (#"%#", text)];
[plist writeToFile:path atomically:YES];
[plist release];