Storing and Retrieving from a Plist [duplicate] - objective-c

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];
}

Related

Write array to plist and fill tableview

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

cocoa and objective c save, edit and load files

hello I am trying to create a text file that will then store some data
- (IBAction)saveUser:(id)sender{
NSString *name = [nameField stringValue];
NSString *weight = [weightField stringValue];
NSDate *date = [datePick dateValue];
}
I want to be able to create a file that stores the following information and uses the name field as the name of the file. I also want to be able to load the file and read that data from it
Any help is appreciated
Thanking You
This is quite simple. But you might want to look into NSMutableDictionary instead. Both NSString and Dictionary have methods writeToFile:#"filename.txt".
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setValue:[nameField stringValue] forKey:#"name"];
[dict setValue:[weightField stringValue] forKey:#"weight"];
[dict setValue:date forKey:#"date"];
[dict writeToFile:name atomically:YES];
you read from the file the same way,
NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithContentsOfFile:name];
As simple as it gets
I think you may get some informations from class NSFileManager, such as like this,
[fileManager createFileAtPath:filePath contents:contentData attributes:NULL];
the contentData is NSData, and it includes the content of what you want to save, the filename is in filePath that you need to set.
Thanks!

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);

Copying JSON response dictionary to plist

I have a dictionary containing a JSON response and a plist file. I want to update the values in my plist file with the JSON response values. How would I do this?
this is what i did, im working on it now, but im getting there:
JSON to dictionary:
NSString *jsonString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
//NSLog(#"%#",jsonString);
NSArray *result = [jsonString JSONValue];
for(NSDictionary *dictionary in result){
return dictionary; //if you are getting more then one row, do something here
}
Saving the dictionary:
id plist = plistDict;
NSString *errorDesc;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:#"Data.plist"];
NSLog(#"%#",plistPath);
NSData *xmlData;
NSString *error;
xmlData = [NSPropertyListSerialization dataFromPropertyList:plist
format:NSPropertyListXMLFormat_v1_0
errorDescription:&error];
if(xmlData) {
if ([xmlData writeToFile:plistPath atomically:YES]) {
NSLog(#"Data successfully saved.");
}else {
NSLog(#"Did not managed to save NSData.");
}
}
else {
NSLog(#"%#",errorDesc);
[error release];
}
}
if you want to update values, I would say you should open the plist, place it in a dictionary, update the value in the dictionary, and save the dictionary to the plist again.
Hope this helps.
If you are working under Mac OS X 10.7 or iOS 5, there is a Foundation class called NSJSONSerialization that will read/write JSON files. Converting JSON to plist will be as simple as: (Implying you have ARC or GC on)
NSString *infile = #"/tmp/input.json"
NSString *oufile = #"/tmp/output.plist"
[[NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:infile]
options:0
error:NULL] writeToFile:oufile
atomically:YES];
However a conversion from plist to JSON will be more troublesome since NSDate and NSData objects cannot appear in JSONs. You may need to check the contents of the file and store the NSData and NSDate in an alternate way (like NSData as Base-64 strings and NSDate as their UNIX times)