transforming a plist in another nsdictionary - objective-c

I'm not english, new to objective c and new to this website. But i hope you will understand my problem. I tried to use the search engine but i couldn't find a answer...
THE PROBLEM:
i have a plist file like this
<plist version="1.0">
<array>
<dict>
<key>ID</key>
<string>001</string>
<key>CAT</key>
<string>A</string>
<key>TITLE</key>
<string>AAAA01</string>
</dict>
<dict>
<key>ID</key>
<string>002</string>
<key>CAT</key>
<string>A</string>
<key>TITLE</key>
<string>AAAA02</string>
</dict>
<dict>
<key>ID</key>
<string>003</string>
<key>CAT</key>
<string>B</string>
<key>TITLE</key>
<string>BBBB01</string>
</dict>
.....
</array>
</plist>
so i have many entries like this. every entry has a category (CAT) like in my example "A" and "B".
now i need a code to transform this to the following:
NSArray
NSDictionary
CAT => "A"
VALUES => {"AAAA01","AAAA02"}
NSDictionary
CAT => "B"
VALUES => {"BBBB01", ...}
ETC.
MY SOLUTION:
i get the plist with the following code
NSString *path = [[NSBundle mainBundle] pathForResource:#"Dictonary" ofType:#"plist"];
arrayIndex = [[NSArray alloc] initWithContentsOfFile:path];
Now i have everything saved in the arrayIndex but then i dont find a way to transform the code in a new array to get my wanted result.
please can anybody help me?
THANK YOU very much!

This is straight programming.
It is more easily done in two steps saving trying to find an entry to add to.
// First create a dictionary of CAT and the values,
NSMutableDictionary *tempDict = [NSMutableDictionary dictionary];
for (NSDictionary *item in arrayIndex) {
NSString *cat = [item valueForKey:#"CAT"];
NSMutableArray *tempArray = [tempDict valueForKey:cat];
if (!tempArray) {
tempArray = [NSMutableArray array];
[tempDict setValue:tempArray forKey:cat];
}
NSString *v = [item valueForKey:#"TITLE"];
[tempArray addObject:v];
}
NSLog(#"tempDict: %#", tempDict);
// This may well be a good final result
// This step transforms the dictionary into a list of dictionaries
NSMutableArray *newList = [NSMutableArray array];
NSArray *keys = [[tempDict allKeys] sortedArrayUsingSelector:#selector(compare:)];
for (NSString *cat in keys) {
[newList addObject:[NSDictionary dictionaryWithObjectsAndKeys:
cat, #"CAT",
[tempDict valueForKey:cat], #"VALUES",
nil]];
}
NSLog(#"newList: %#", newList);

Related

Get details from plist file with objective-c

Here is my problem.
I can't seem to figure out how to access the "Details" key in the same level as the "Name" key once search for a specific name key. Maybe I'm missing something?
I know you can get "Details" via [dict objectForKey:#"Details"] but I'm not sure how to get the one on the same levels as the one that was searched for.
Code:
- (IBAction)ScoringButtonView:(id)sender {
ScoringViewController *svController = [[ScoringViewController alloc] initWithNibName:#"ScoringView" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:svController animated:YES];
UIButton *scoringButton = (UIButton*)sender;
NSLog(#"Scoring is %# ", scoringButton.currentTitle);
svController.ScoringName = scoringButton.currentTitle;
NSString *path = [[NSBundle mainBundle] pathForResource:#"Scoring" ofType:#"plist"];
NSArray *plistData = [NSArray arrayWithContentsOfFile:path];
for (NSDictionary *dict in plistData) {
if ([[dict objectForKey:#"Name"] isEqualToString:scoringButton.currentTitle]) {
NSLog(#"Scoring == %# ", scoringButton.currentTitle);
// svController.ScoringInfo =
}
}
plist:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
<dict>
<key>Name</key>
<string>Standard</string>
<key>Details</key>
<string>dagsdfgds</string>
</dict>
<dict>
<key>Name</key>
<string>Advanced</string>
<key>Details</key>
<string>gfdsgdfsgdsfg</string>
</dict>
</array>
</plist>
I'm not sure what the confusion is. You already know how to get the value for the Name key. Getting the value for the Details key is the same:
for (NSDictionary *dict in plistData) {
if ([dict[#"Name"] isEqualToString:scoringButton.currentTitle]) {
NSString *details = dict[#"Details"];
}
}
Note how I used modern Objective-C syntax instead of the old style use of objectForKey:.
//This method should work fine
//Enumeration method is better than for loop
NSString *filePath = [[NSBundle mainBundle] pathForResource:#“LanguageList” ofType:#"json"];
NSString *myJSON = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSJSONReadingAllowFragments error:NULL];
NSError *error = nil;
NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:[myJSON dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&error];
[dict[#"result"] enumerateObjectsUsingBlock:^(id _Nonnull objList, NSUInteger idx, BOOL * _Nonnull stop) {
NSLog(#“Values %#”,obj);
*stop = YES;
}
}];

How do I write a Dictionary to an array in a plist?

I have a plist that is structured like this:
<dict>
<key>memos</key>
<array>
<dict>
<key>title</key>
<string>First Memo</string>
<key>content</key>
<string>Testing one two three</string>
<key>category</key>
<string>testing</string>
</dict>
<dict>
<key>title</key>
<string>Test</string>
<key>content</key>
<string>This is a test memo.</string>
<key>category</key>
<string>testing</string>
</dict>
</array>
</dict>
I'm reading it into an array like this:
self.memos = [NSMutableArray array];
NSString *path = [[NSBundle mainBundle] pathForResource:#"Memos" ofType:#"plist"];
NSDictionary *tempDictionary = [NSDictionary dictionaryWithContentsOfFile:path];
NSArray *tempArray = [tempDictionary objectForKey:#"memos"];
for(id dict in tempArray) {
NSString *title = [dict objectForKey:#"title"];
NSString *content = [dict objectForKey:#"content"];
NSString *category = [dict objectForKey:#"category"];
Memo *m = [[Memo alloc] initWithTitle:title content:content category:category];
[self.memos addObject:m];
}
My question is: how do I add a new Memo (a dictionary of three strings) to the plist (specifically, the array of Memo dictionaries in my plist)?
You have to grab the plist in a NSDictionary, then read the Memos array into a NSMutableArray, add a object to it, then save the mutable memos array as memos in the dictionary and write it back to the plist file.
Change this line:
NSArray *tempArray = [tempDictionary objectForKey:#"memos"];
to
self.memos = [tempDictionary objectForKey:#"memos"];
Hope it helps...
and make sure you write back the self.memos data back to the file.
Also note you cannot edit a file in the bundle. You need to ensure that you copy it over to the documents directory before you start editing it and save it.
Try this:
[tempArray addObject:NewDictionary That you want to insert];
then add this temp array to TempDictionary.
[tempDictionary setObject:tempArray forKey:#"memos"];
and then save tempdictionary to file.
[tempDictionary writeToFile:path atomically:YES];
Hope it Helps!!

read multi-array from plist

I can't get it work to have the 8 items from the plist below.
I have a plist "settings.plist". Now I wan't from vragen -> category (self.catagorie - 1) -> question. The 8 items. But the array keeps empty.
What am I doing wrong?
Code:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"instellingen.plist"];
NSMutableDictionary *instellingen = [NSMutableDictionary dictionaryWithContentsOfFile:path];
NSArray *vragen = [instellingen objectForKey:#"vragen"];
NSArray *cata = [vragen objectAtIndex: (self.catagorie-1)];
NSArray *question = [cata objectAtIndex: 0];
NSLog(#"count: %i", [question count]);
Plist file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>vragen</key>
<array>
<array> <--catagorydata
<array> <-- questiondata
<string>vraag</string>
<string>A</string>
<string>B</string>
<string>C</string>
<string>D</string>
<string>1</string>
<string>standaard</string>
<string></string>
</array>
<array>
<string>vraag2</string>
<string>A</string>
<string>B</string>
<string>C</string>
<string>D</string>
<string>1</string>
<string>afbeelding</string>
<string>afbeelding.jpg</string>
</array>
</array>
</array>
<key>firstBoot</key>
<true/>
<key>regelAtRuntime</key>
<true/>
</dict>
</plist>
First of all this line
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"instellingen.plist"]; ?
should be
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"settings.plist"];
I also had to delete these from the dictionary:
<--catagorydata
<-- questiondata
Besides the two things above, there is nothing wrong with your code or your dictionary.
After making those changes I tested your code and the output I got was:
tester[69637:c07] size of dict 3
tester[69637:c07] count: 8
which is correct according to the .plist file
So your problem is at the first 4 lines. Make sure your file is in Documents directory (use something like the following code to see whats going wrong)
NSLog(#"Path : %#",path);
I copied the file in the project folder (because I used the simulator) and used the following code and everything worked fine
NSBundle* b=[NSBundle mainBundle];
NSURL* path1=[b URLForResource:#"settings" withExtension:#"plist"];
NSMutableDictionary *instellingen = [NSMutableDictionary dictionaryWithContentsOfURL:path1];
NSLog(#"size of dict %d",[instellingen count]);
NSArray *vragen = [instellingen objectForKey:#"vragen"];
NSArray *cata = [vragen objectAtIndex: 0];
NSArray *question = [cata objectAtIndex: 0];
NSLog(#"count: %i", [question count]);
Just a quick read, but looks like you have an array of "categoryData" items, that contains an array of questionData items; questionData items are strings.
NSArray *vragen = [instellingen objectForKey:#"vragen"]; // count = 1
NSArray *cata = [vragen objectAtIndex: (self.catagorie-1)]; // count = 2
NSString *question = [cata objectAtIndex: 0];
Recommend you add some breakpoints and look at your data. OR, NSLog(#"data = %#", cata); etc.

How to Load Plist to UITableView Objective-C

I have this plist setup:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
<dict>
<key>area</key>
<string>area1</string>
<key>shop</key>
<string>shop1</string>
<key>location</key>
<string>2nd Floor</string>
<key>coordinates</key>
<string>14.733836,121.058221</string>
</dict>
<dict>
<key>area</key>
<string>area1</string>
<key>shop</key>
<string>shop2</string>
<key>location</key>
<string>Ground Floor</string>
<key>coordinates</key>
<string>14.733836,121.058221</string>
</dict>
<dict>
<key>area</key>
<string>area2</string>
<key>shop</key>
<string>shop1</string>
<key>location</key>
<string>2nd Floor</string>
<key>coordinates</key>
<string>14.656918,121.029795</string>
</dict>
<dict>
<key>area</key>
<string>area2</string>
<key>shop</key>
<string>shop2</string>
<key>location</key>
<string>Ground Floor</string>
<key>coordinates</key>
<string>14.656918,121.029795</string>
</dict>
</array>
</plist>
How can I plot this inside my UITableView? My header titles will be the key "area" while the table cell labels the key "shop" and the subtitle labels the key "location". The coordinates key will be used to plot it on the mapview that loads when the user taps the table cell.
Thanks in advance!
- (UITableViewCell *)tableView:cellForRowAtIndexPath:
NSDictionary *dict = [array objectAtIndex: indexPath.section];
cell.textLabel.text = [dict objectForKey: #"shop"];
cell.detailTextLabel.text = [dict objectForKey: #"location"];
- (NSString *)tableView:titleForHeaderInSection:
NSDictionary *dict = [array objectAtIndex: indexPath.section];
NSString *area = [dict objectForKey: #"area"];
return area;
- (void)tableView:didSelectRowAtIndexPath:
NSDictionary *dict = [array objectAtIndex: indexPath.section];
NSString *coordinates = [dict objectForKey: #"coordinates"];
newViewController.coordinates = coordinates
You have to create 3 NSDictionary.
Dict 1: titles
Dict 2: celltexts
Dict 3: subtitles
NSDictionary *dictTitles = [[NSDictionary dictionaryWithContentsOfFile:#"filepathtoyourplist"] valueForKey:#"Titles"];
Then put it into an array
NSArray *titleArray = [[NSArray alloc] initWithDictionary:dictTitles];
in your titlesForHeaderInSection
headertitle = [titlearray objectAtIndex:indexPath.row];
Do the steps for cell text and subtitle again.
you can try this :
//In your .h file
NSArray *array;
//In your .m file
- (void)viewDidLoad {
// Some code...
NSString *path = [[NSBundle mainBundle] pathForResource:#"filename" ofType:#"plist"];
array = [NSArray arrayWithContentsOfFile:path];
// Some code...
}
Then you create a new NSObject class and for each cell you init your object, for example :
MyClass *newInstance = [[MyClass alloc] init];
newInstance.area = [array objectForKey:#"area"];
newInstance.shop = [array objectForKey:#"shop"];
newInstance.location = [array objectForKey:#"location"];
newInstance.coordinates = [array objectForKey:#"coordinates"];
Hope it helps :)

Reading plist file

I created plist with big base of different animals in it (keys) and added this plist in my project.
Type of every animal is NSDictionary. In every dictionary there are 5 more keys - characteristics of these animals (). I would like to go through every animal and if I match a certain characteristics of this animal, I put this animal in another array.
So, I tried to make a code:
NSArray *newArray = [[NSArray alloc]initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"animals" ofType:#"plist"]];
for (int i = 0;[newArray objectAtIndex:i];i++)
{
if ([[newArray objectAtIndex:i]objectForKey:#"minAge"] == [NSNumber numberWithInt:3])
{
[array addObject:[[newArray objectAtIndex:i]objectForKey:#"name"]];
}
}
So objectAtIndex:i is an animal and minAge is one of it's characteristics. But my code does not work.
I do it for the first time, so what I have done wrong ? Thanks!
UPDATE:
Thank you, your plist works normally ! But I still cant understand why doesn't work mine plist:
Anyway, thank you so much ! I didn't eat and sleep while I was solving this problem :)
You helped me a lot !
NSArray The Return value will be nil if the file can’t be opened or if the contents of the file can’t be parsed into an array.
I suspect the issue is you need to put the contents in a NSDictionary rather than a NSArray
NSDictionary *theDict = [NSDictionary dictionaryWithContentsOfFile:plistFile];
Edit.Further to my answer
NSMutableArray *mutableArray =[[NSMutableArray alloc] initWithObjects:nil];
NSDictionary *mainDictionary = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"animals" ofType:#"plist"]];
//--get parent dictionary/Array named animals which holds the animals dictionary items
NSDictionary *parentDictionary = [mainDictionary objectForKey:#"animals"];
//---enumerate through the dictionary objects inside the parentDictionary
NSEnumerator *enumerator = [parentDictionary objectEnumerator];
id value;
while ((value = [enumerator nextObject])) {
if ([[value valueForKey:#"minAge"] isEqualToNumber:[NSNumber numberWithInt:3]])
{
[mutableArray addObject:[value valueForKey:#"name"]];
}
}
If the animal dictionaries are not inside of a parent dictionary or Array, use something like this
NSMutableArray *mutableArray =[[NSMutableArray alloc] initWithObjects:nil];
NSDictionary *mainDictionary = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"animals" ofType:#"plist"]];
//---enumerate through the dictionary objects
NSEnumerator *enumerator = [mainDictionary objectEnumerator];
id value;
while ((value = [enumerator nextObject])) {
if ([[value valueForKey:#"minAge"] isEqualToNumber:[NSNumber numberWithInt:3]])
{
[mutableArray addObject:[value valueForKey:#"name"]];
}
}
Edit. 1.
Try it with this plist.
Make sure you use a plain text editor to paste it into and save as a plist file
Edit.2 .
I have now updated my plist to match yours. Although the other one worked. I felt it would make more sense that we are using the same.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Whale</key>
<dict>
<key>name</key>
<string>Whale</string>
<key>isMale</key>
<true/>
<key>color</key>
<string>blue</string>
<key>maxAge</key>
<integer>8</integer>
<key>minAge</key>
<integer>3</integer>
</dict>
<key>Dolphin</key>
<dict>
<key>maxAge</key>
<integer>20</integer>
<key>name</key>
<string>Dolphin</string>
<key>isMale</key>
<false/>
<key>color</key>
<string>blue</string>
<key>minAge</key>
<integer>15</integer>
</dict>
</dict>
</plist>
Also, here is another example showing how to compare the boolean and number together
NSMutableArray *theAnimalMatched =[[NSMutableArray alloc] initWithObjects:nil];
NSDictionary *mainDictionary = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"data1" ofType:#"plist"]];
//---enumerate through the dictionary objects inside the rootDictionary
NSEnumerator *enumerator = [mainDictionary objectEnumerator];
id returnValue;
while ((returnValue = [enumerator nextObject])) {
if ( [[returnValue valueForKey:#"isMale" ] boolValue] && [[returnValue valueForKey:#"minAge"] isEqualToNumber:[NSNumber numberWithInt:3]] && [[returnValue valueForKey:#"color"] isEqualToString:#"blue"] )
{
[theAnimalMatched addObject:[returnValue valueForKey:#"name"]];
}
}
Instead of the following line
if ([[newArray objectAtIndex:i]objectForKey:#"minAge"] == [NSNumber numberWithInt:3])
try the following
if ( [[[newArray objectAtIndex:i]objectForKey:#"minAge"] isEqualToNumber:[NSNumber numberWithInt:3]])