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.
Related
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
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);
This question already has answers here:
How to Save NSMutableArray into plist in iphone
(4 answers)
Closed 9 years ago.
I have NSMutableArray with name "add" that has in self name of cell (in UITableView)
I want store this "add" NSMutableArray in .plist file.
this is "add" code:
//NSArray *NaMe;
//NSMutableArray *add;
//NSMutableArray *all;
for (int i =0; i<11; i++) {
NSIndexPath *indexPath = [self.Table indexPathForSelectedRow];
NaMe = [[all objectAtIndex:(indexPath.row)+i]objectForKey:#"name"];
if(!add){
add = [NSMutableArray array];
}
[add addObject:NaMe];
}
NSLog(#"%#",add);
this add show me name of cell and I want store this name in .plist file.
I assume you want to save the plist for persistence.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = paths[0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"Names.plist"];
[add writeToFile:filePath atomically:YES];
To read back from plist
NSArray *array = [NSArray arrayWithContentsOfFile:filePath];
NSArray*pListpaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString*pListdocumentsDirectory = [pListpathsobjectAtIndex:0];
NSString*pListpath = [pListdocumentsDirectory stringByAppendingPathComponent:#"Apps.plist"]; NSFileManager*pListfileMgr = [NSFileManager defaultManager];
//Create a plist if it doesn't alread exist
if (![pListfileMgrfileExistsAtPath: pListpath])
{
NSString*bundle = [[NSBundle mainBundle]pathForResource:#"Apps" ofType:#"plist"];
[pListfileMgrcopyItemAtPath:bundletoPath: pListpatherror:&error];
}
//Write to the plist
NSMutableDictionary*thePList = [[NSMutableDictionary alloc] initWithContentsOfFile: pListpath];
[thePList setObject:[NSString stringWithFormat:#"YourContent"] forKey:#"Related Key"];
[thePList writeToFile: pListpathatomically: YES];
Try This Sample Code
The solution is quite simple.
Create an NSArray containing your NSMutableArray, then write it to a path.
NSArray *yourArray=[NSArray arrayWithObjects:<#(id), ...#>, nil];
NSArray *yourPath = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *libDir = [yourPath objectAtIndex:0];
NSString *loc = [libDir stringByAppendingString:#"/anyfilename.plist"];
[yourArray writeToFile:loc atomically:YES];
Fetch your array using:
yourPath = [bundle pathForResource:#"anyfilename" ofType:#"plist"];
yourArray = (yourArray!= nil ? [NSArray arrayWithContentsOfFile:loc] : nil);
user this code
#define DOC_DIR [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]
NSArray *NaMe;
NSMutableArray *add;
NSMutableArray *all;
for (int i =0; i<11; i++) {
NSIndexPath *indexPath = [self.Table indexPathForSelectedRow];
NaMe = [[all objectAtIndex:(indexPath.row)+i]objectForKey:#"name"];
if(!add){
add = [NSMutableArray array];
}
[add addObject:NaMe];
}
NSLog(#"%#",add);
[self writeDataToPlistFromArray:add];
-(void) writeDataToPlistFromArray:(NSArray *) dataArray
{
NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObjectsAndKeys:dataArray,#"Root", nil];
NSString *path = [DOC_DIR stringByAppendingPathComponent:#"Names.plist"];
[dic writeToFile:path atomically:YES];
}
I have a .plist file which have this structure,
I want to add or replace the Item 5. I am using this code
NSError *error ;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"Introduction.plist"];
NSMutableArray *data = [[NSMutableArray alloc] initWithContentsOfFile:path];
NSString *comment = str;
[data replaceObjectAtIndex:1 withObject:comment];
[data writeToFile:path atomically:YES];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:path]) {
NSString *bundle = [[NSBundle mainBundle] pathForResource:#"Introduction" ofType:#"plist"];
[fileManager copyItemAtPath:bundle toPath:path error:&error];
}
If I change replaceObjectAtIndex: to 5 it changes my plist structure, and I don't want that.
How can I insert/replace the text at the row 5 (Item 5) of particular Index?
You structure has an array of arrays.
[data replaceObjectAtIndex:1 withObject:comment];
By this code you are replacing an array at index 1 with a string. Do you specifically need to insert to 5th index or do you just need to add it to existing sub array?
NSMutableArray *subArray = [data[sectionIndex] mutableCopy];
if (!subArray) {
subArray = [NSMutableArray array];
}
if (rowIndex<[subArray count]) {
[subArray replaceObjectAtIndex:rowIndex withObject:comment];
}else{
[subArray addObject:comment];
}
[data replaceObjectAtIndex:sectionIndex withObject:subArray];
[data writeToFile:path atomically:NO];
Access the subArray, make it mutable and add or insert at specific index. If you are trying to insert don't forget to include a check if the index is not greater than count of that array.
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"];