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];
}
Related
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 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);
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"];
I am trying to save an NSMutable Array and NSString into plist and then if it exists initialize the value from plist. However when I re run the app, the values do not get initialize as it is suppose to. So far the following is what I have.
if (self = [super init]) {
NSString *path=[self getFileUrl];
NSFileManager *fm = [[NSFileManager alloc] init];
if ([fm fileExistsAtPath:path]) {
_history = [d objectForKey:#"stringKey"];
class=[d objectForKey: #"ArrayKey"];
}
NSDictionary *d;
However the values are not getting initialized as per the plist. Is it the way I am extracting the values from the dictionary?
here is my function that saving json into plist in nscachesdirectory
-(void)saveproducts{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString* plistPath = [documentsPath stringByAppendingPathComponent:#"Products.plist"];
NSDictionary*dict = [NSDictionary dictionary];
NSMutableArray *types = [NSMutableArray array];
NSArray *dictArray = [NSArray array];
NSArray *dictKeys = [NSArray array];
NSArray *productObjects = [NSArray array];
NSArray *productKeys = [NSArray array];
for (int i=0; i<appDelegate.products.count; i++) {
NSMutableArray *tmpProds = [NSMutableArray array];
NSString *t_ID = [[appDelegate.products objectAtIndex:i] valueForKey:#"id"];
NSString *t_image = [[appDelegate.products objectAtIndex:i] valueForKey:#"image"];
NSString *t_name =[[appDelegate.products objectAtIndex:i] valueForKey:#"name"];
NSArray *products = [[appDelegate.products objectAtIndex:i] valueForKey:#"products"];
NSDictionary *productsDict = [NSDictionary dictionary];
for (int j=0; j<products.count; j++) {
NSString *p_id = [[products objectAtIndex:j] valueForKey:#"id"];
NSString *p_name = [[products objectAtIndex:j] valueForKey:#"name"];
NSString *p_name2 = [[products objectAtIndex:j] valueForKey:#"name2"];
NSString *image = [[products objectAtIndex:j] valueForKey:#"image"];
NSString *typeID = [[products objectAtIndex:j] valueForKey:#"type_id"];
NSString *active = [[products objectAtIndex:j] valueForKey:#"active"];
NSString *available = [[products objectAtIndex:j] valueForKey:#"available"];
NSString *desc = [[products objectAtIndex:j] valueForKey:#"description"];
NSString *price = [[products objectAtIndex:j] valueForKey:#"price"];
if ([p_name2 isEqual:[NSNull null]]) {
p_name2 =#"undefined";
}
if ([desc isEqual:[NSNull null]]) {
desc = #"";
}
productObjects = [NSArray arrayWithObjects:p_id,p_name,p_name2,image,typeID,active,available,desc,price, nil];
productKeys = [NSArray arrayWithObjects:#"id",#"name",#"name2",#"image",#"type_id",#"active",#"available",#"desc",#"price", nil];
productsDict = [NSDictionary dictionaryWithObjects:productObjects forKeys:productKeys];
[tmpProds addObject:productsDict];
if (![image isEqualToString:#""]) {
[foodImages addObject:image];
}
}
dictArray = [NSArray arrayWithObjects:t_ID,t_image,t_name,tmpProds, nil];
dictKeys = [NSArray arrayWithObjects:#"id",#"image",#"name",#"products", nil];
dict = [NSDictionary dictionaryWithObjects:dictArray forKeys:dictKeys];
[types addObject:dict];
}
NSDictionary* plistDict = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects:types, nil] forKeys:[NSArray arrayWithObjects:#"ptype", nil]];
NSString *error = nil;
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
if(plistData)
{
[plistData writeToFile:plistPath atomically:YES];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool:YES forKey:#"cached"];
[defaults synchronize];
}
else
{
NSLog(#"Error log: %#", error);
}
}
and this one reading plist
-(void)loadFromplist{
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString* plistPath = [documentsPath stringByAppendingPathComponent:#"Products.plist"];
NSData *plistData = [[NSFileManager defaultManager] contentsAtPath:plistPath];
NSDictionary *dict = (NSDictionary*)[NSPropertyListSerialization propertyListFromData:plistData mutabilityOption:NSPropertyListMutableContainersAndLeaves format:nil errorDescription:nil];
productsArray = [dict valueForKey:#"ptype"];
[self.tableView reloadData];
}
I am trying to save in my iOS app some data. I use the following code :
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"yourPlist.plist"];
//inserting data
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setValue:categoryField.text forKey:#"Category"];
[dict setValue:nameField.text forKey:#"Name"];
[dict setValue:eventField.text forKey:#"Event"];
NSMutableArray *arr = [[NSMutableArray alloc] init];
[arr addObject:dict];
[arr writeToFile: path atomically:YES];
//retrieving data
NSMutableArray *savedStock = [[NSMutableArray alloc] initWithContentsOfFile: path];
for (NSDictionary *dict in savedStock) {
NSLog(#"my Note : %#",dict);
}
However the NSLog shows me only the last data... I suppose that i am overwriting here..I cant see why though!
How can i continue to save dictionaries in the array without overwriting? Any ideas?
Since you are making a model object it would be better if you include save, remove, findAll, findByUniqueId kind of logic built into it. Will make working with the model object very simple.
#interface Note : NSObject
#property (nonatomic, copy) NSString *category;
#property (nonatomic, copy) NSString *name;
#property (nonatomic, copy) NSString *event;
- (id)initWithDictionary:(NSDictionary *)dictionary;
/*Find all saved notes*/
+ (NSArray *)savedNotes;
/*Saved current note*/
- (void)save;
/*Removes note from plist*/
- (void)remove;
Save a note
Note *note = [Note new];
note.category = ...
note.name = ...
note.event = ...
[note save];
Delete from saved list
//Find the reference to the note you want to delete
Note *note = self.savedNotes[index];
[note remove];
Find all saved notes
NSArray *savedNotes = [Note savedNotes];
Source Code
Replace:
NSMutableArray *arr = [[NSMutableArray alloc] init];
[arr addObject:dict];
[arr writeToFile: path atomically:YES];
With:
NSMutableArray *arr = [[NSMutableArray alloc] initWithContentsOfFile: path];
[arr addObject:dict];
[arr writeToFile: path atomically:YES];
You need to first read in the data, then APPEND the new dictionary to the old one. So read the file first, then append the new dictionary, then save.
FULL CODE:
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setValue:categoryField.text forKey:#"Category"];
[dict setValue:nameField.text forKey:#"Name"];
[dict setValue:eventField.text forKey:#"Event"];
[self writeDictionary:dict];
- (void)writeDictionary:(NSDictionary *)dict
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"yourPlist.plist"];
NSMutableArray *savedStock = [[NSMutableArray alloc] initWithContentsOfFile: path];
if(!savedStock) {
savedStock = [[[NSMutableArray alloc] initiWithCapacity:1];
}
[savedStock addObject:dict];
// see what';s there now
for (NSDictionary *dict in savedStock) {
NSLog(#"my Note : %#",dict);
}
// now save out
[savedStock writeToFile:path atomically:YES];
}