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.
Related
I successfully added my dictionary to plist but when i add 2nd time it remove my old dictionary from my plist.
Here is my code :
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *plistPath = [documentsPath stringByAppendingPathComponent:#"favQuote.plist"];
NSDictionary *plistDict = [[NSDictionary alloc] initWithObjectsAndKeys:self.txtQuote.text,#"quote",self.lblAuthor.text,#"author",nil];
NSError *error = nil;
NSData *plistData = [NSPropertyListSerialization dataWithPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 options:NSPropertyListWriteStreamError error:&error];
if(plistData)
{
[plistData writeToFile:plistPath atomically:YES];
NSLog(#"Data saved sucessfully");
}
else
{
NSLog(#"Data not saved");
}
How do I add my new dictionary without losing old data?
You should store your dictionary of array in your document directory something like,
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *plistPath = [documentsPath stringByAppendingPathComponent:#"favQuote.plist"];
NSFileManager *manager = [NSFileManager defaultManager];
NSMutableArray *arr = [[NSMutableArray alloc]init];
if ( [manager fileExistsAtPath:plistPath]) {
NSData *data = [NSData dataWithContentsOfFile:plistPath];
arr = (NSMutableArray*)[NSKeyedUnarchiver unarchiveObjectWithData:data];
}
NSDictionary *plistDict = [[NSDictionary alloc] initWithObjectsAndKeys:#"test",#"quote",#"test2",#"author",nil];
[arr addObject:plistDict];
NSData *plistData = [NSKeyedArchiver archivedDataWithRootObject:arr];
if(plistData)
{
[plistData writeToFile:plistPath atomically:YES];
NSLog(#"Data saved sucessfully");
}
else
{
NSLog(#"Data not saved");
}
then you can retrieve and use your values like,
NSMutableArray *arr1 = [[NSMutableArray alloc]init];
if ( [manager fileExistsAtPath:plistPath]) {
NSData *data = [NSData dataWithContentsOfFile:plistPath];
arr1 = (NSMutableArray*)[NSKeyedUnarchiver unarchiveObjectWithData:data];
}
if (arr1.count > 0) {
NSDictionary *firstDic = [arr1 objectAtIndex:0];
}
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 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];
I am having trouble to write new dictionaries in my plist file where I want to save data each time the user fill a form.
The code I am using right now only overwrite the data and doesn´t save the previous dictionary as wanted.
here the code :
//////////// Save data into 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.titlestring = titleexperiencia.text;
self.descriptionstring = descriptionexperiencia.text;
self.coordinadastring = [self deviceLocation];
// create dictionary with values in UITextFields
NSDictionary *plistDict = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects: titlestring, descriptionstring,coordinadastring, nil] forKeys:[NSArray arrayWithObjects: #"Title", #"Description", #"Coordinate", 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];
NSLog(#"Saved in Data Plist");
}
else
{
NSLog(#"Error in saveData: %#", error);
[error release];
}
I also tried to use AddObject: instead of writeToFile: but that make the App crash.
Well, the crash is probably being caused because you're overreleasing the error variable.
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!