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];
}
Related
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 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);
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];
}
in my app I want to save user playlist in a plist file and load this playlist when app start.
this is the code that I use to save:
if (self.backgroundMusicItems) {
NSMutableArray *songsID = [[NSMutableArray alloc] initWithCapacity:0];
MPMediaItem *item;
for (item in self.backgroundMusicItems.items) {
NSNumber *songId = [item valueForProperty:MPMediaItemPropertyPersistentID];
[songsID addObject:songId];
}
NSString *documentdir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *filePath = [documentdir stringByAppendingPathComponent:#"playlist.plist"];
[songsID writeToFile:filePath atomically:YES];
}
and this is the code that I use to load:
NSString *documentdir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *filePath = [documentdir stringByAppendingPathComponent:#"playlist.plist"];
NSArray *myArray = [[NSArray alloc] initWithContentsOfFile:filePath];
NSMutableSet *predicates = [[NSMutableSet alloc] initWithCapacity:0];
if (myArray.count > 0) {
NSNumber *songId;
for (songId in myArray) {
MPMediaPropertyPredicate *predicate = [MPMediaPropertyPredicate predicateWithValue:songId forProperty:MPMediaItemPropertyPersistentID];
[predicates addObject:predicate];
}
MPMediaQuery *query = [[MPMediaQuery alloc] initWithFilterPredicates:predicates];
NSArray *mediaItems = [query items];
if (mediaItems.count > 0) [GameOptions sharedClass].backgroundMusicItems = [[MPMediaItemCollection alloc] initWithItems:mediaItems];
}
myArray contains 2 items but [query items] method return 0 items. Where I'm wrong??
You're asking for songs where MPMediaItemPropertyPersistentID is set to the value for song1 AND song2 - which will always return zero results as it's logically impossible for any songs to match two different MPMediaItemPropertyPersistentIDs.
You need to run a query for each persistent id.