Write array to plist and fill tableview - objective-c

I have a method that returns a an NSMutableArray with a bunch of strings. How can I add this array (with strings) to a plist file and use it to fill an UITableView with it? Thanks

Create an array with Values
NSArray *array = [NSArray arrayWithObjects:#"One",
#"Two",
#"Three",
#"Four", nil];
Create File Path in Document Directory, you can write file there, not in Application Bundle
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentFolder = [path objectAtIndex:0];
NSString *filePath = [documentFolder stringByAppendingFormat:#"myfile.plist"];
Save Array to Plist file
[array writeToFile:filePath atomically:YES];
NSLog(#"file Stored at %#",filePath);
To Read Array From plist Use Following Code
NSArray *plistArray = [NSArray arrayWithContentsOfFile:filePath];
NSLog(#"%#",plistArray);
Though if you are still not getting you can refer tutorial here

Related

Storing and Retrieving from a Plist [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
iOS: store two NSMutableArray in a .plist file
I've always refrained from using plists as I'm not really sure how to use one.
Could anyone give a simple code example of using a plist? I'm interested in saving an NSArray or NSDictionary to a plist and then retrieving it again later.
Are there any advantages/disadvantages to storing either an NSArray or an NSDictionary? Also, are there any rules with regards to what you can or can't store in a plist?
You can store the following data types in a .plist file as value:
NSArray
NSMutableArray
NSDictionary
NSMutableDictionary
NSData
NSMutableData
NSString
NSMutableString
NSNumber
NSDate
With an NSDictionary you can store in a plist an associative array composed by some key-value pair. Use the NSArray if you only want to save a data series.
To save one of the object above on a plist file simply write:
- (NSString *)dataFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:#"yourFileNameHere"];
}
//Write to the plist
[myArray writeToFile:[self dataFilePath] atomically:YES];
//Read from the plist
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
}

Create plist file via code

I want to create a plist file like this:
in code, and then it will be in the Caches folder.
I already know how to fetch the data.
You can do it like this:
//Create a Mutant Dictionary
NSMutableDictionary *theMutantDict = [[NSMutableDictionary alloc] init];
//Fill it with data
[theMutantDict setObject:#"John" forKey:#"Name"];
[theMutantDict setObject:#"Doe" forKey:#"Lastname"];
//Then search for cache dir
NSString *libraryDir = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
NSUserDomainMask, YES) objectAtIndex:0];
NSString *cacheDir = [libraryDir stringByAppendingPathComponent:#"Caches"];
//Then write the file
NSString *filePath = [cacheDir stringByAppendingString:#"/TheFile.plist"];
[theMutantDict writeToFile:filePath atomically:YES];
Just use the writeToFile-method of NSArray to store the array in a plist and arrayWithContentsOfFile to load it.
[self.array writeToFile:path atomically:YES];
self.array = [[NSArray arrayWithContentsOfFile:path];
// or in case you need to add/remove objects (NSMutableArray):
self.array = [[[NSArray arrayWithContentsOfFile:path] mutableCopy] autorelease];
If you got your data stored in an NSArray it's as easy as this:
// filling array with data ...
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachePath = [paths objectAtIndex:0];
NSString *plistPath = [cachePath stringByAppendingPathComponent:#"my_nsarray_data.plist"];
[klasserArray writeToFile:plistPath atomically:YES];
// other stuff ...

Creating new dictionary when saving data to plist

So I am saving 3 NSStrings from 3 UITextFields to a property list. This works fine, but everytime I save something new, the app overwrites the data that was saved before. So basically there is only 1 Dictionary used, but i want the app to create a new dictionary everytime i save something new, so that no data gets deleted. I have no Idea how i could do this, so please help me!! :)
Code:
NSMutableArray *array = [NSMutableArray arrayWithCapacity:3];
NSArray *keys = [NSArray arrayWithObjects:#"1",#"2",#"3", nil];
[array addObject:[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSString stringWithFormat:#"%#",lab.text],[NSString stringWithFormat:#"%#",lab1.text],[NSString stringWithFormat:#"%#",lab2.text], nil] forKeys:keys]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"data.plist"];
[array writeToFile:path atomically:YES];
Use a NSMutableArray to which you add each new dictionary object and then write that array to data.plist.
Is there any reason why you alloc the array with capacity? I would just use [[NSMutableArray alloc] init], then add your objects.
Also, I had trouble saving NSMutableDictionaries in the NSUserDefaults, so what I ended up doing was just saving the dictionary to a file with
[dict writeToFile:filePath atomically:NO];
and initWithContentsOfFile or initWithContentsOfURL depending if I wanted to load a local or Internet file.
I should add, you can writeToFile, initWithContentsOf* for NSMutableArray as well.
Ok I've got it:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"data.plist"];
NSLog(#"path='%#'",path);
NSFileManager *nfm = [[NSFileManager alloc] init];
if([nfm fileExistsAtPath:path])
{
// if file exists, get its contents, add more entries and write back
NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:path];
NSArray *keys = [NSArray arrayWithObjects:#"4",#"5",#"6",nil];
[array addObject:[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSString stringWithFormat:#"%#",lab.text],[NSString stringWithFormat:#"%#",lab1.text],[NSString stringWithFormat:#"%#",lab2.text], nil] forKeys:keys]];
NSLog(#"modified array=%#",array);
BOOL ok = [array writeToFile:path atomically:YES];
if(!ok){
NSLog(#"Unable to write appended file");
return;
}
} else {
// if file doesn't exist, create a new one
NSMutableArray *array = [[NSMutableArray alloc] init];
NSArray *keys = [NSArray arrayWithObjects:#"1",#"2",#"3",nil];
[array addObject:[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSString stringWithFormat:#"%#",lab.text],[NSString stringWithFormat:#"%#",lab1.text],[NSString stringWithFormat:#"%#",lab2.text], nil] forKeys:keys]];
NSLog(#"new array=%#",array);
BOOL ok = [array writeToFile:path atomically:YES];
if(!ok){
NSLog(#"Unable to write new file");
return;
}
}

Save NSDictionary to plist

I am using the code found in this post: Mulitple Arrays From Plist, with the same plist formatting.
This works successfully, however I do not know how to save the created arrays back into a plist, in the same format.
How would I achieve this?
EDIT: It is not so much the saving that I need, but the forming of the data to save.
The plist is an array of dictionaries with strings and their corresponding keys.
All the strings with a certain key are put into an array of their own.
How would I put that array back into the correct positions in the array of dictionaries, ready to save?
Here's the simplest way:
NSDictionary* dict = ...;
[dict writeToFile:#"..." atomically:YES];
See the documentation for -writeToFile:atomically:.
Don't forget to create myPlistFile.plist and add it in your application resource folder.
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
you could scan paths here and search myPlistFile.plist using for loop.
NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:#"myPlistFile.plist"];
if (![[NSFileManager defaultManager] fileExistsAtPath: plistPath])
{
NSString *bundle = [[NSBundle mainBundle] pathForResource:#"myPlistFile" ofType:#"plist"];
[[NSFileManager defaultManager] copyItemAtPath:bundle toPath:plistPath error:&error];
}
[myDict writeToFile:plistPath atomically: YES];
And conversely, to load a NSDictionary FROM a file:
+ (id)dictionaryWithContentsOfFile:(NSString *)path;

iOS: store two NSMutableArray in a .plist file

I want to store two NSMutableArray that I use as global array in AppDelegate. These two array are also store with NSUserDefaults. Now I want to know how I must create this file and how can I store these two array everytime I modify them. Can You help me?
Create an NSArray containing your two NSMutableArrays.
NSArray *array = [NSArray arrayWithObjects:<#(id), ...#>, nil];
Write the array to a file.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *libraryDirectory = [paths objectAtIndex:0];
NSString *location = [libraryDirectory stringByAppendingString:#"/somefilename.plist"];
[array writeToFile:location atomically:YES];
Load the array from the file.
NSString *path = [bundle pathForResource:#"file" ofType:#"plist"];
NSArry *array = (path != nil ? [NSArray arrayWithContentsOfFile:location] : nil);