Convert dictionary items from plist to NSArray - objective-c

I have a plist with the following architecture/structure:
dictionary
key1
item1
key2
item2
key3
item3
dictionary
...
and i want to load item (item1) for the first key (key1) of every dictionary to an NSArray, so that i can load the nsarray into a UITableView.
i cam to this point:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"data.plist"];
NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:path];
and then i wanted to add something like this:
tablearray = [array objectsForKey:#"key1"];
but that doesn't exist as command. Seems like i need some help there... :)

You can loop over the Array and add the Objekts that way:
NSMutableArray *tablearray = [NSMutableArray arrayWithCapacity:[array count]];
for (NSDictionary *dict in array) {
[tablearray addObject:[dict objectForKey:#"key1"]];
}

Apple provides pList programming guide which describes how to read from a pList and also writes into it. You can go throug it.
We will get the data from the pList as NSData and convert it into NSDictionary, by using the following method,
NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
NSDictionary *temp = (NSDictionary *)[NSPropertyListSerialization
propertyListFromData:plistXML
mutabilityOption:NSPropertyListMutableContainersAndLeaves
format:&format
errorDescription:&errorDesc];
you can add the response dictionary intro an array using the
NSMutableArray * myArray = [NSMutableArray alloc] init];
//temp is the response dictionary
NSArray * myKeys = [temp allKeys];
for (int index = 0; index<[myKeys count]; index++) {
id value = [temp valueForKey:[myKeys objectAtIndex:index]];
[myArray addObject:value];
}
use the myArray now.
I think this is what you needed.

Related

Write an NSMutableArray to a file and load it back

I'm doing some exercises about writing to and loading from a file.
I've created an NSString, then written it to a file, and then loaded an NSString again. Simple.
How can I do this with an NSMutableArray of NSStrings, or better an NSMutableArray of my own class?
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
#autoreleasepool {
// insert code here...
//write a NSString to a file
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"file.txt"];
NSString *str = #"hello world";
NSArray *myarray = [[NSArray alloc]initWithObjects:#"ola",#"alo",#"hello",#"hola", nil];
[str writeToFile:filePath atomically:TRUE encoding:NSUTF8StringEncoding error:NULL];
//load NSString from a file
NSArray *paths2 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory2 = [paths2 objectAtIndex:0];
NSString *filePath2 = [documentsDirectory2 stringByAppendingPathComponent:#"file.txt"];
NSString *str2 = [NSString stringWithContentsOfFile:filePath2 encoding:NSUTF8StringEncoding error:NULL];
NSLog(#"str2: %#",str2);
}
return 0;
}
Printed: str2: hello world
If you want to write your array as a plist, you can
// save it
NSArray *myarray = #[#"ola",#"alo",#"hello",#"hola"];
BOOL success = [myarray writeToFile:path atomically:YES];
NSAssert(success, #"writeToFile failed");
// load it
NSArray *array2 = [NSArray arrayWithContentsOfFile:path];
NSAssert(array2, #"arrayWithContentsOfFile failed");
For more information, see Using Objective-C Methods to Read and Write Property-List Data in the Property List Programming Guide.
But, f you want to preserve the mutability/immutability (i.e. the precise object types) of your objects, as well as open up the possibility of saving a wider array of object types, you might want to use an archive rather than a plist:
NSMutableString *str = [NSMutableString stringWithString:#"hello world"];
NSMutableArray *myarray = [[NSMutableArray alloc] initWithObjects:str, #"alo", #"hello", #"hola", nil];
//save it
BOOL success = [NSKeyedArchiver archiveRootObject:myarray toFile:path];
NSAssert(success, #"archiveRootObject failed");
//load NSString from a file
NSMutableArray *array2 = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
NSAssert(array2, #"unarchiveObjectWithFile failed");
While I illustrate the technique with an array, it works with any object that conforms to NSCoding (which includes many of the basic Cocoa classes like strings, arrays, dictionaries, NSNumber, etc.). If you want to make your own classes work with NSKeyedArchiver, then you must make them conform to NSCoding, too. For more information, see the Archives and Serializations Programming Guide.
This document at Apple walks you through the process.

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!

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

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