Saving data into plist with iOS - ios

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.

Related

Unable to save data to plist

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.

Save string to plist remove old data

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];
}

how to add multiple arrays in plist file programmatically in iPhone

I want to create plist file with multiple array and array as Root type.I can add multiple array in dictionary but I want to add all array in one array programmatically.How is it possible to create plist file programmatically and write array data into it.Please guide me and give some sample links.Thanks.
Here is my code to add array in dictionary :
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"Demo.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path])
{
NSString *bundle = [[NSBundle mainBundle] pathForResource:#"Demo" ofType:#"plist"];
[fileManager copyItemAtPath:bundle toPath: path error:&error];
}
firstArray = [[NSMutableArray alloc] initWithObjects:#"15-5-123",#"15-5-12",nil];
secondArray = [[NSMutableArray alloc] initWithObjects:#"TestFiling",#"TestFiling",nil];
thirdArray = [[NSMutableArray alloc] initWithObjects:#"15132561",#"15135601", nil];
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
[dictionary setObject:firstArray forKey:#"firstArray"];
[dictionary setObject:secondArray forKey:#"secondArray"];
[dictionary setObject:thirdArray forKey:#"thirdArray"];
[dictionary writeToFile:path atomically:NO];
NSDictionary *dictionary1;
dictionary1 = [NSDictionary dictionaryWithContentsOfFile:path];
NSLog(#"dictionary1 %#",dictionary1);
this code is working fine for dictionary but i want to add arrays in array.
The first section of your code is fine, you just need to switch the second part to using an array:
NSMutableArray *array = [[NSMutableDictionary alloc] init];
[array addObject:firstArray];
[array addObject:secondArray];
[array addObject:thirdArray];
[array writeToFile:path atomically:NO];
NSArray *array1 = [NSArray arrayWithContentsOfFile:path];
NSLog(#"array1 %#", array1);

Store NSString value in plist file in iOS

My question in UIActionSheet button add to favourite click and copy UITableViewCell in nextview so i am using string value in store dynamic create plist file and first time click cell and open UIActionSheet and add to favourite UIButton click and copy 1 cell properly but second time add to favourite click and not add 2 item store only 1 new array item so my question in plist file at a time 1 value is add so any answer..`
Store data from plist
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex ==2) {
FavoritesViewController *objfav= [self.storyboard instantiateViewControllerWithIdentifier:#"fav"];
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *plistPath = [documentsPath stringByAppendingPathComponent:#"manuallyData.plist"];
[arrplist addObject:quote];
NSDictionary *plistDict = [[NSDictionary alloc] initWithObjects: [NSArray arrayWithObjects: arrplist, nil] forKeys: [NSArray arrayWithObjects: #"icon", nil]];
NSString *error = nil;
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
if(plistData)
{
[plistData writeToFile:plistPath atomically:YES];
}
else
{
}
objfav.arrCopy = arrplist;
[self.navigationController pushViewController:objfav animated:YES];
}
}
fetch data from dynamic create plist file in nextview
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *plistPath = [documentsPath stringByAppendingPathComponent:#"manuallyData.plist"];
if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath])
{
plistPath = [[NSBundle mainBundle] pathForResource:#"manuallyData" ofType:#"plist"];
}
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
arrCopy = [dict objectForKey:#"icon"];

iOS New array in plist with new key overwrites old array with different key

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];

Resources