Store NSString value in plist file in iOS - 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"];

Related

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 set multiple dictionary on array on my plist file?

I am creating one simple suitable view with one button.
When button pressed new view spend and one user contact list display.
In this view two field User Name and User Address are placed.
Now my question is when I pressed Save button of fill my text field the content save in array of dictionary form and display the name of person on my table view.
But when I again fill the data for new user and save it then my new dictionary overwrite on my old dictionary.
Please help me i want to require every dictionary for each person.
The code is
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *plistPath = [documentsPath stringByAppendingPathComponent:#"sample.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:plistPath]) {
NSString *sourcePath = [[NSBundle mainBundle] pathForResource:#"sample" ofType:#"plist"];
[fileManager copyItemAtPath:sourcePath toPath:plistPath error:nil];
}
NSLog(#"%#",plistPath);
NSString *personName = self.nameField.text;
NSString *personAddress = self.addressField.text;
NSString *nameKay = #"name";
NSString *AddressKey = #"address";
NSArray *values = [[NSArray alloc] initWithObjects:personName,personAddress, nil];
NSArray *keys = [[NSArray alloc] initWithObjects: nameKay, AddressKey, nil];
NSDictionary *dict = [[NSDictionary alloc] initWithObjects:values forKeys:keys];
[self.plistContainer addObjectsFromArray:dict];
NSLog(#"%#", self.plistContainer);
[self.plistContainer writeToFile:plistPath atomically:YES];
[self dismissViewControllerAnimated: YES completion: nil];
Image Is
App Image is

Writing/ Appending data to Plist returns nill

I am writing data to plist with always returns me the nil value.. I have to append data also to the previous values of array. But Values are always null..
Below is the code:
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:#"a.plist"];
// set the variables to the values in the text fields
// create dictionary with values in UITextFields
NSDictionary *plistDict = [NSDictionary dictionaryWithObject:#"c" forKey:#"Id"];
if ([[NSFileManager defaultManager] fileExistsAtPath:plistPath])
{
array = [[NSMutableArray alloc] initWithContentsOfFile:plistPath];
[array addObject:plistDict];
[array writeToFile:plistPath atomically:YES];
NSLog(#"array%#",array);
}
else
{
NSArray *array = [NSArray arrayWithObject:plistPath];
[array writeToFile:plistPath atomically:YES];
}
If I understand your question correctly, I tested the code with just one little change i.e, Added array declaration and it's working fine. Please pardon me if this is not the issue.
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:#"a.plist"];
// set the variables to the values in the text fields
NSMutableArray *array;
// create dictionary with values in UITextFields
NSDictionary *plistDict = [NSDictionary dictionaryWithObject:#"c" forKey:#"Id"];
if ([[NSFileManager defaultManager] fileExistsAtPath:plistPath])
{
array = [[NSMutableArray alloc] initWithContentsOfFile:plistPath];
[array addObject:plistDict];
[array writeToFile:plistPath atomically:YES];
NSLog(#"array%#",array);
}
else
{
NSArray *array = [NSArray arrayWithObject:plistPath];
[array writeToFile:plistPath atomically:YES];
}

Accessing Plist from user documents instead of NSBundle

Hello I have the following code which works perfect, it finds the Plist and assigns the NSDictionary to my NSArray called landingSites. The only problem is I want the user to be able to add sites so need to store the Plist in the user documents instead of the NSBundle:
plistPath = [[NSBundle mainBundle] pathForResource:#"Data" ofType:#"plist"];
NSMutableDictionary *newDictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
dictionaryKeys = [newDictionary allKeys];
self.landingSites = [dictionaryKeys sortedArrayUsingSelector:#selector(compare:)];
self.dictionaryFromPlist = newDictionary;
[Picker selectRow:0 inComponent:0 animated:NO];
for(NSString *parent in dictionaryKeys)
{
NSDictionary *parentData = [dictionaryFromPlist objectForKey:parent];
NSArray *child = [parentData objectForKey:#"Name"];
NSLog(#"%#", child);
}
So far I have produced the code below, but whenever I run the program, the if-statement ALWAYS executes as if the plist in never copied to the user documents. Also I do not know how to attach the NSDictionary contents to my landingSites array as I did above. Please help
(void) viewDidLoad {
[super viewDidLoad];
NSError *error;
NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask,YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"Data.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:path]) {
NSLog(#"copying database to users documents");
NSString *pathToSettingsBundle = [[NSBundle mainBundle] pathForResource:#"Data" ofType:#"plist"];
[fileManager copyItemAtPath:pathToSettingsBundle toPath:path error:&error];
}
else{
NSLog(#"users database already configured");
}
NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask,YES);
NSDocumentationDirectory is wrong. You are looking for NSDocumentDirectory or NSLibraryDirectory.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

Adding Array to PLIST

I am trying to add and array to a Root array in my plist:
And is not working. Here's my code:
-(IBAction)addName:(id)sender{
NSArray *arrayValues = [NSArray arrayWithObjects: nameLabel.text, nameDate.text, nameValue.text, nil];
NSString *plistpath = [[NSBundle mainBundle] pathForResource:#"Names" ofType:#"plist"];
NSMutableArray *namesNew = [[NSMutableArray alloc] initWithContentsOfFile:plistpath];
[namesNew addObject:arrayValues];
[namesNew writeToFile:plistpath atomically:YES];
}
What am I doing wrong? Thanks!
You need to move the file to NSDocumentDirectory. Then edit the plist file.
For example:
Moving to NSDocumentDirectory:
-(NSDictionary *)copyBundleToDocuments
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [documentPaths objectAtIndex:0];
NSString *documentPlistPath = [documentsDirectory stringByAppendingPathComponent:#"Names.plist"];
NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
NSString *bundlePlistPath = [bundlePath stringByAppendingPathComponent:#"Names.plist"];
//if file exists in the documents directory, get it
if([fileManager fileExistsAtPath:documentPlistPath])
{
NSMutableDictionary *documentDict = [NSMutableDictionary dictionaryWithContentsOfFile:documentPlistPath];
return documentDict;
}
//if file does not exist, create it from existing plist
else
{
NSError *error;
BOOL success = [fileManager copyItemAtPath:bundlePlistPath toPath:documentPlistPath error:&error];
if (success) {
NSMutableDictionary *documentDict = [NSMutableDictionary dictionaryWithContentsOfFile:documentPlistPath];
return documentDict;
}
return nil;
}
}
Then get the plist:
-(void)plistArray:(NSArray*)array
{
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//getting the plist file name:
NSString *plistName = [NSString stringWithFormat:#"%#/Names.plist",
documentsDirectory];
NSMutableArray *namesNew = [[NSMutableArray alloc] initWithContentsOfFile:plistName];
[namesNew addObject:arrayValues];
[namesNew writeToFile:plistName atomically:YES];
return nil;
}
The plist should be a dictionary as the base object instead of an array.
NSMutableDictionary *namesNew = [NSMutableDictionary dictionaryWithContentsOfFile:plistpath];
[namesNew setObject: arrayValues forKey: #"Root"];
[namesNew writeToFile:plistpath atomically:YES];
You cant write your plist to the bundle you need to use NSDocumentDirectory or NSCachesDirectory
Just copy your plist to bundle the overwrite it.
Note: learn the difference between NSCachesDirectory and NSDocumentDirectory
https://developer.apple.com/icloud/documentation/data-storage/
Copy your plist from bundle to documents(in below code caches), you need to this only one time if your plist in your bundle, I prefer using this code in appdelegate.m when - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"Names.plist"];
NSString *plistInDocuments=#"Names.plist";
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:plistInDocuments];
NSError *error = nil;
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]){
[[NSFileManager defaultManager] copyItemAtPath:sourcePath
toPath:dataPath
error:&error];
}
NSLog(#"Error description-%# \n", [error localizedDescription]);
NSLog(#"Error reason-%#", [error localizedFailureReason]);
Get your file and overwrite it
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *plistInDocuments=#"Names.plist";
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:plistInDocuments];
//add object here
NSMutableArray *namesNew = [[NSMutableArray alloc] initWithContentsOfFile:dataPath];
[namesNew addObject:arrayValues];
NSError *error = nil;
if ([myFile writeToFile:dataPath options:NSDataWritingAtomic error:&error]) {
// file saved
} else {
// error writing file
NSLog(#"Unable to write plist to %#. Error: %#", dataPath, error);
}

Resources