How to dissect and reorganize info in an NSDictionary - iphone

So I have an array of NSDictionaries, each NSDictionary has a bunch of key/value pairs pertaining to aspects of a photo (from Flickr).
I'm making an app that has a UITableViewController whose cells should be each of the different categories of the photos. So in pseudocode, I'm trying to construct a new NSDictionary (with keys being categories of photos, values being the NSDictionaries of the photos that contains that key). I'm iterating through each NSDictionary in the initial array, getting the category tags, and saying, if my new NSDict doesn't contain this key, make a new key to an empty array. Then add the current NSDict to that array. I'm getting consistent errors, not sure why.
Here's the diluted code.
photoList = [FlickrFetcher photosWithTags:[NSArray arrayWithObjects: #"CS193p_SPoT", nil]];
NSLog(#"%#", photoList);
categories = [[NSDictionary alloc] init];
NSArray *temp = [[NSArray alloc] init];
for (id obj in photoList) {
temp = [[obj objectForKey:#"tags"] componentsSeparatedByString:#" "];
for (id string in temp) {
if (![categories objectForKey:string]) {
NSMutableArray *arr = [[NSMutableArray alloc] init];
[categories setObject:arr forKey:string];
//[arr release];
}
NSMutableArray *photos = [categories objectForKey:string];
[photos addObject:obj];
[categories setObject:photos forKey:string];
}
}
Thanks!

NSDictionary doesn't have a method setObject:forKey:. You need an NSMutableDictionary.
self.categories = [NSMutableDictionary dictionary];
Other than that, please do use Joost's excellent rewrite of your code.
SIGABRT, just so you know, most likely means that an assertion somewhere failed. In this case, it may be an assertion all the way down in CoreFoundation*; CF checks for mutability when you try to access a dictionary like that and causes an interrupt if the object isn't mutable.
*I have just learned about the CF source's availability recently and have been looking through it, so this may be just "new thing" bias and incorrect.

I don't notice any errors (syntax-errors, that is) in your code, however here is an updated piece of code which has been implemented a bit cleaner (and without memory leaks)
self.photoList = [FlickrFetcher photosWithTags:[NSArray arrayWithObjects: #"CS193p_SPoT", nil]];
NSLog(#"%#", photoList);
self.categories = [NSDictionary dictionary];
for (NSDictionary *obj in photoList) {
NSArray *temp = [[obj objectForKey:#"tags"] componentsSeparatedByString:#" "];
for (NSString *string in temp) {
NSMutableArray *photos = [categories objectForKey:string];
if (!photos) {
photos = [NSMutableArray array];
[categories setObject:photos forKey:string];
}
[photos addObject:obj];
}
}
If it's not working please tell us the exact warning, and were it is caused.

Related

Can´t add objects to mutable array which returns nil

I´m doing an app and I can´t get a mutable array to accept objects. I´v tried setting breakpoints to see what´s happening but it keeps saying that the mutable array is nil. Does anyone has an answer?
My code:
- (void)save:(id) sender {
// All the values about the product
NSString *product = self.productTextField.text;
NSString *partNumber = self.partNumberTextField.text;
NSString *price = self.priceTextField.text;
NSString *quantity = self.quantityTextField.text;
NSString *weigh = self.weighTextField.text;
NSString *file = [self filePath];
//Singleton class object
Object *newObject = [[Object alloc] init];
newObject.product = product;
newObject.partNumber = partNumber;
newObject.price = price;
newObject.quantity = quantity;
newObject.weigh = weigh;
//Array declaration
mutableArray = [[NSMutableArray alloc]initWithContentsOfFile: file];
[mutableArray addObject:newObject];
[mutableArray writeToFile:file atomically:YES];
}
While initWithContentsOfFile: can be called on an NSMutableArray, it was inherited from NSArray. The return value is an NSArray which is not mutable. If you want to add objects to your mutable array, you have to do something like this:
mutableArray = [[[NSMutableArray alloc] initWithContentsOfFile: file] mutableCopy];
[mutableArray addObject:newObject];
[mutableArray writeToFile:file atomically:YES];
Now, the addObject: call should work.
Best regards.
[NSMutableArray initWithContentsOfFile:] returns nil by default if the file can't be opened or parsed. Are you sure the file you're loading exists and is formatted correctly?
Try to check with break point on
mutableArray = [[NSMutableArray alloc]initWithContentsOfFile: file];
Line. Move your cursor on mutableArray if it shows you __NSArrayI that means it is an immutable array i.e. you cant update it and if it shows you __NSArrayM that means it is a mutable array and you can update this array.
In your case you're getting immutable array thats why you cant update it.
So you have two way to get mutable Array from this file -
Method:1
mutableArray = [[[NSMutableArray alloc] initWithContentsOfFile: file] mutableCopy];
Method:2
NSArray *anyArray = [[NSArray alloc]initWithContentsOfFile: file];
mutableArray = [[NSMutableArray alloc]initWithArray:anyArray];
In both case mutableArray woud be a mutable Array. You can update it.

Retrive values from NSDictionary

I am trying to retrieve the values from my NSDictionary however I am running into errors, I was wondering if someone might be able to help me with my solution.
I have 18 values, not all are shown here that I am checking, when the correct key is reached I would like to take the value in the NSDictionary and pass it into one of my NSString variables.
Below is an example of what I am trying to do however like I say I am having several issues
for (id key in searchData) {
if ([[searchData objectForKey:key] isEqualToString:#"Code"]) {
codeSeries = [searchData objectForKey:key];
}
else if ([[searchData objectForKey:key] isEqualToString:#"ID"]) {
IDSeries = [searchData objectForKey:key];
}
// ...
However, when I try to log out any of the values, they all return Null. I have checked the dictionary before hand and the values are all most definitely in there, so I am thinking there is something wrong with my code above.
Any help would be greatly appreciated.
Update
This is how I create the NSDictionary
//start of mymethod...
NSDictionary *sendSeriesDictionary = [[NSDictionary alloc] init];
// Keys for sendSeriesDictionary
NSArray *keys = [NSArray arrayWithObjects:#"Code", #"ID", nil];
// Objects for keys that are for sendSeriesDictionary
NSArray *objects = [NSArray arrayWithObjects: [NSNull null], IdString, nil];
// Add keys and objects to NSDictionary
sendSeriesDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
[engineRequests SeriesSearch:sendSeriesDictionary]; // this is where I send the NSDictionary over to where I want to read it.
//end of mymethod
You've got several problems. First, you mix up keys and values (like Tom said). Second, you have a possible memory leak where you create the dictionary, or at least a unnecessary instantiation.
Try this for creating the dictionary:
// Keys for sendSeriesDictionary
NSArray *keys = [NSArray arrayWithObjects:#"Code", #"ID", nil];
// Objects for keys that are for sendSeriesDictionary
NSArray *objects = [NSArray arrayWithObjects: [NSNull null], IdString, nil];
// Add keys and objects to NSDictionary
NSDictionary *sendSeriesDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
Retrieving the values can be done like this:
codeSeries = [searchData objectForKey:#"Code"];
IDSeries = [searchData objectForKey:#"ID"];
In your first loop you looped through all the keys, got their values and then compared those to the key again. Which makes no sense.
Are you mixing keys and values ?
Maybe you just want codeSeries = [searchData objectForKey:#"Code"]; ?

help on sorting NSMutableDictionary strings that are URL images

i want to populate the tablecell with title and imageurl from xml list.
i manage to store the title (NSMutableDictonary *sections )and imageURL (NSMutableDictonary *sectionsImg) into 2 NSMutableDictionary respectively.
/*******This is in viewDidLoad***/
Directory *allDirectory = [appDelegate.directories objectAtIndex:0];
for (allDirectory in appDelegate.directories)
{
NSDictionary *dica = [NSDictionary dictionaryWithObject:allDirectory.dirTitle forKey:#"dirTitle"];
NSDictionary *dico = [NSDictionary dictionaryWithObject:allDirectory.imageURL forKey:#"imageURL"];
[dirName addObject:dica];
[dirImage addObject:dico];
//NSLog(#"dic of items : %#",dirImage);
}
for (allDirectory in appDelegate.directories)
{
//retrieve the first letter from every directory title (dirTitle)
NSString * c = [allDirectory.dirTitle substringToIndex:3];
NSString * m = allDirectory.imageURL;
found = NO;
find = NO;
for (NSString *str in [self.sections allKeys])
{
if ([str isEqualToString:c])
{
found = YES;
}
}
for (NSString *stra in [self.sectionsImg allKeys])
{
if([stra isEqualToString:m])
{
find = YES;
}
}
if (!found)
{
[self.sections setValue:[[NSMutableArray alloc]init] forKey:c ];
[self.sectionsImg setValue:[[NSMutableArray alloc]init] forKey:m];
}
if (!find)
{
[self.sectionsImg setValue:[[NSMutableArray alloc]init] forKey:m];
}
}
for (NSDictionary *directory in dirName)
{
[[self.sections objectForKey:[[directory objectForKey:#"dirTitle"] substringToIndex:3]] addObject:directory];
//NSLog(#"hehehe have : %#",sections);
}
for (NSDictionary *directoryImg in dirImage)
{
//[[self.sectionsImg objectForKey:[[directoryImg objectForKey:#"imageURL"] substringFromIndex:0]] addObject:directoryImg];
[[self.sectionsImg objectForKey:[directoryImg objectForKey:#"imageURL"]] addObject:directoryImg];
//NSLog(#"HOHOHO have : %#",sectionsImg);
}
And on cellForRowAtIndexPath i declare a dictionary
NSDictionary *dictionary = [[self.sections valueForKey:[[[self.sections allKeys] sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)] objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
cell.textLabel.text = [dictionary objectForKey:#"dirTitle"];
but when i tried to declare a dictionary for imageURL
NSDictionary *dictionaryImg = [[self.sectionsImg valueForKey:[[[self.sectionsImg allKeys] sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)] objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
it gives me a error :
Terminating app due to uncaught exception 'NSRangeException', reason: '* -[NSMutableArray objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
any idea why? the logic is supposed to be the same where xml title and url can be retrieve and be displayed. Title is retrievable but imageURL is not. Help is deeply appreciated !
You are trying to sort an array... except for the fact your array isn't an array, but a NSDictionary.
Your code isn't the best at the moment. Your getting the idea of Dictionaries wrong and may be confusing them with arrays, so my best guess is your quite new to programming into objective-c.
You have two lists of things, if I'm not mistaken. The first list is the list of names, and the second list is an image corresponding with that name.
Below I'm going to do two things:
Firstly, I'm giving you two ways on how to fix your problem. It has a sample code included and gives you a small explanation with it. The possibility exist you don't understand parts of what I describe. In that case, you should;
Check out the link I described below the two solutions. It has a tutorial which makes you understand everything about arrays, dictionaries, tables and, as a bonus, XML-parsing.
So, in my opinion, you can do two things:
The first one is using an array of NSDictionaries. You'd be using a code which looks like:
NSMutableDictionary *itemOne = [[NSMutableDictionary alloc] init];
NSMutableDictionary *itemTwo = [[NSMutableDictionary alloc] init];
NSMutableArray *listOfAll = [[NSmutableArray alloc] init];
NSString *itemOneName = [[NSString alloc] initWithFormat:#"This is picture 1"];
NSString *itemTwoName = [[NSString alloc] initWithFormat:#"This is picture 2"];
NSData *imageOneData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: #"http://myurl/mypic1.jpg"]];
NSData *imageTwoData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: #"http://myurl/mypic2.jpg"]];
UIImage *itemOneImage = [UIImage imageWithData: imageOneData];
UIImage *itemTwoImage = [UIImage imageWithData: imageTwoData];
[itemOne setObject:itemOneNameString forKey:#"Name"];
[itemOne setObject:itemOneImage forKey:#"Image"];
[itemTwo setObject:itemTwoNameString forKey:#"Name"];
[itemTwo setObject:itemTwoImage forKey:#"Image"];
[listOfAll addObject:itemOne];
[listOfAll addObject:itemTwo];
Anything can be filled using that array. Just use something with a for-loop to iterate through your array.
for (int i = 0; i < [listOfAll count]; i++)
{
NSMutableDictionary *currentItem = [[NSMutableDictionary alloc] initWithDictionary:[listOfAll objectAtIndex:i]];
//Do something with that current item
}
You can also use that index in your tableView. In that case, you have to use your variable section instead of i to get your desired index.
The second one is using two arrays. Imagine you get an image named imageOne with the text imageName. Then you should use:
NSMutableArray *nameList = [[NSMutableArray alloc] init];
[nameList addObject: imageName];
NSMutableArray *imageList = [[NSMutableArray alloc] init];
[imageList addObject: imageOne];
If you want to use a certain item out of those lists, you just have to use the same indexnumber.
For example:
[theTitleLabel setText:[[NSString alloc] initWithFormat:#"%#", [nameList objectAtIndex:x]]];
[theImageView setImage:[imageList objectAtIndex:x]];
Make sure the x's are the same number.
I understand this is all a lot of information, especially if you're new to Objective - C. A tutorial exists which gives you a lot of information about how to use arrays, dictionaries and table views. As a bonus, you get to know a little about XML-parsing.
I suggest you walk through that tutorial and do everything and read everything it says. This should give you a nice start into the world of programming in iPhones.
Good luck!

Releasing NSArray containing NSDictionary objects

I am having difficulty getting my head around memory management in the following segment of code on iPhone SDK 3.1.
// Create array to hold each PersonClass object created below
NSMutableArray *arrayToReturn = [[[NSMutableArray alloc] init] autorelease];
NSArray *arrayOfDictionaries = [self generateDictionaryOfPeople];
[arrayOfDictionaries retain];
for (NSDictionary *dictionary in arrayOfDictionaries) {
PersonClass *aPerson = [[PersonClass alloc] init];
for (NSString *key in [dictionary keyEnumerator]) {
if ([key isEqualToString:[[NSString alloc] initWithString: #"FIRST_NAME"]])
aPerson.firstName = [dictionary objectForKey:key];
else if ([key isEqualToString:[[NSString alloc] initWithString: #"LAST_NAME"]])
aPerson.lastName = [dictionary objectForKey:key];
}
// Add the PersonClass object to the arrayToReturn array
[arrayToReturn addObject: aPerson];
// Release the PersonClass object
[aPerson release];
}
return arrayToReturn;
The [self generateDictionaryOfPeople] method returns an array of NSDictionary objects. Each NSDictionary object has two keys "FIRST_NAME" and "LAST_NAME" with a person's first name and last name as the respective data. The code is looping through each dictionary object in the arrayOfDictionaries array and assigning the dictionary data to the relevant property of an aPerson (PersonClass) object. This object is then added to an array which is returned from this method.
When running instruments I am getting a leak for the dictionary objects contained in the arrayOfDictionaries array. The code within the [self generateDictionaryOfPeople] method is calling [dictionaryObject release] on each NSDictionary object as it is created and added to the array, which makes the retain count on the object 1 (as adding the object to the array would make the retain count 2, but then my release message decrements it back to 1).
I assume this leak is because I am never releasing the arrayOfDictionaries array, and thus the NSDictionary objects within the array are never released. If I attempt to release the array at the end of the above segment of code I get a "message sent to deallocated instance" error. I understand why this is occurring, because I am assigning the aPerson object data within a dictionary item (that I am subsequently releasing) but I don't know where else I can release the arrayOfDictionaries array. Any help would be greatly appreciated.
Thanks!
EDIT: Below is the implementation for [self generateDictionaryOfPeople]
- (NSArray *)generateDictionaryOfPeople {
NSMutableArray *arrayFromDatabase = [[[NSMutableArray alloc] init] autorelease];
// ** Query the database for data **
while ( there are rows being returned from the database ) {
// Declare an NSMutableDictionary object
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
// Loop through each column for that row
for ( while there are columns for this row ) {
columnTitle = title_of_column_from_database
columnData = data_in_that_column_from_database
// Add to the dictionary object
[dictionary setObject:columnData forKey:columnTitle];
// Release objects
[columnName release];
[columnTitle release];
}
// Add the NSMutableDictionary object to the array
[arrayFromDatabase addObject:dictionary];
// Release objects
[dictionary release];
}
// Return the array
return arrayFromDatabase;
}
Here,
if ([key isEqualToString:[[NSString alloc] initWithString: #"FIRST_NAME"]])
aPerson.firstName = [dictionary objectForKey:key];
else if ([key isEqualToString:[[NSString alloc] initWithString: #"LAST_NAME"]])
aPerson.lastName = [dictionary objectForKey:key];
Replace them with
if ([key isEqualToString:#"FIRST_NAME"])
aPerson.firstName = [dictionary objectForKey:key];
else if ([key isEqualToString:#"LAST_NAME"])
aPerson.lastName = [dictionary objectForKey:key];
The problem of the leak is you're creating 1 ~ 2 NSString-s per loop without -release-ing them. If you need constant NSString-s, just directly use them.
I am still getting the original leak due to not releasing the arrayOfDictionaries array.
That means you forgot to autorelease it in generateDictionaryOfPeople.
You need to review the memory management rules.
You are not releasing arrayFromDatabase. (The simplest way to avoid this kind of mistake is to use factories and autorelease as early as possible rather than defer releases manually. In this case, use [NSMutableDictionary dictionary] instead of [[NSMutableDictionary alloc] init].)

Create a dictionary property list programmatically

I want to programatically create a dictionary which feeds data to my UITableView but I'm having a hard time with it. I want to create a dictionary that resembles this property list (image) give or take a couple of items.
I've looked at "Property List Programming Guide: Creating Property Lists Programmatically" and I came up with a small sample of my own:
//keys
NSArray *Childs = [NSArray arrayWithObjects:#"testerbet", nil];
NSArray *Children = [NSArray arrayWithObjects:#"Children", nil];
NSArray *Keys = [NSArray arrayWithObjects:#"Rows", nil];
NSArray *Title = [NSArray arrayWithObjects:#"Title", nil];
//strings
NSString *Titles = #"mmm training";
//dictionary
NSDictionary *item1 = [NSDictionary dictionaryWithObject:Childs, Titles forKey:Children , Title];
NSDictionary *item2 = [NSDictionary dictionaryWithObject:Childs, Titles forKey:Children , Title];
NSDictionary *item3 = [NSDictionary dictionaryWithObject:Childs, Titles forKey:Children , Title];
NSArray *Rows = [NSArray arrayWithObjects: item1, item2, item3, nil];
NSDictionary *Root = [NSDictionary dictionaryWithObject:Rows forKey:Keys];
// NSDictionary *tempDict = [[NSDictionary alloc] //initWithContentsOfFile:DataPath];
NSDictionary *tempDict = [[NSDictionary alloc] initWithDictionary: Root];
I'm trying to use this data of hierachy for my table views.
So I was wondering how can I can create my property list (dictionary) programmatically so that I can fill it with my own arrays.
I'm still new with iPhone development so bear with me. ;)
This is a situation where "teach a man to fish" is a vastly more helpful approach than "give a man a fish". Once you understand the basic principles and the NSDictionary API, it becomes much easier to craft your own custom solution. Here are a few observations and learning points:
The method +dictionaryWithObject:forKey: is used to create an NSDictionary with a single key-value pair. It will not accept comma-separated arguments after each colon (:) in the method call, just one. To create a dictionary with multiple key-value pairs, use one of 2 related methods: +dictionaryWithObjects:forKeys: which accepts two NSArray objects containing values and keys, or +dictionaryWithObjectsAndKeys: which alternates (object, key, object, key) with a terminating nil argument.
Simplify the creation code. You don't need a million local variables just to create the thing. Use inline arguments where it makes sense. One way to do this it to build up your dictionary in code as an NSMutableDictionary, then (if necessary) make an immutable copy of it by calling -copy on it. (Remember that a copy method returns a new object that you must release to avoid memory leaks.) That way you don't have to have a variable for every single value so you can do a "one shot" creation of the structure(s) at each level.
Use +arrayWithObject: for creating an NSArray with a single object.
(Style suggestions) Never use an uppercase letter to begin the name of a variable, method, or function. (Notice that SO highlights leading-caps variables like class names.) It will certainly help others who read your code from being confused about your intent by your naming scheme.
Just to give you a flavor of what creating the dictionary in the linked image might look like in code... (I'm ignoring your chosen variable names and using both different approaches for completeness.)
NSDictionary *item1 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:#"Screen J",[NSNumber numberWithInt:3],nil]
forKeys:[NSArray arrayWithObjects:#"Title",#"View",nil]];
NSDictionary *item2 = [NSDictionary dictionaryWithObjectsAndKeys:
#"Screen I", #"Title",
[NSArray arrayWithObject:item1], #"Children",
nil];
...
I am not sure I understand the basic objective here.
It seems like at runtime, you are constructing a deep dictionary with many child nodes. But you are constructing this all with static code... why can you not simply make a plist (like the one you had an image of) and read that into an NSDictionary? Both NSDictionary and NSArray have methods that let you simply read in a file and get a whole filled out object. Then it is WAY easier to edit and to understand. That method is dictionaryWithContentsOfFile.
If all of the data is truly created at runtime before it is put into the dictionary, then it seems like you would want a very different, recursive, style of code rather than the flat examples given.
Lastly, I personally dislike the dictionaryWithObjects:forKeys: method in NSDictionary for building a dictionary. If you have to do things that way I greatly prefer the alternate method dictionaryWithObjectsAndKeys: which does the same thing but keeps the keys with the objects:
NSDictionary *item1 = [NSDictionary dictionaryWithObjectsAndKeys:
#"Screen J",
#"Title",
[NSNumber numberWithInt:3],
#"View"];
NSMutableDictionary *topLevel = [NSMutableDictionary dictionary];
NSMutableDictionary *item1 = [NSMutableDictionary dictionary];
NSString *item1title = [NSString stringWithString:#"Title 1"];
NSMutableDictionary *item1children = [NSMutableDictionary dictionary];
// create children
NSString *item1child1 = [NSString stringWithString:#"item 1, child 1"];
NSMutableDictionary *item1child2 = [NSMutableDictionary dictionary];
NSString *item1child2title = [NSString stringWithString:#"Title 1-2"];
NSMutableDictionary *item1child2children = [NSMutableDictionary dictionary];
NSString *item1child2child1 = [NSString stringWithString:#"item 1, child 2, child 1"];
NSString *item1child2child2 = [NSString stringWithString:#"item 1, child 2, child 2"];
[item1child2 setObject:item1child2title forKey:#"Title"];
[item1child2children setObject:item1child2child1 forKey:#"item 1 child2 child 1"];
[item1child2children setObject:item1child2child2 forKey:#"item 1 child2 child 2"];
[item1child2 setObject:item1child2children forKey:#"children"];
// add children to dictionary
[item1children setObject:item1child1 forKey:#"item1 child1"];
[item1children setObject:item1child2 forKey:#"item1 child2"];
// add to item 1 dict
[item1 setObject:item1title forKey:#"Title"];
[item1 setObject:item1children forKey:#"children"];
NSMutableDictionary *item2 = [NSMutableDictionary dictionary];
NSString *item2title = [NSString stringWithString:#"Title"];
NSMutableDictionary *item2children = [NSMutableDictionary dictionary];
NSString *item2child1 = [NSString stringWithString:#"item 2, child 1"];
NSString *item2child2 = [NSString stringWithString:#"item 2, child 2"];
NSString *item2child3 = [NSString stringWithString:#"item 2, child 3"];
// add children to dictionary
[item2children setObject:item2child1 forKey:#"item2 child1"];
[item2children setObject:item2child2 forKey:#"item2 child2"];
[item2children setObject:item2child3 forKey:#"item2 child3"];
// add to item 2 dict
[item2 setObject:item2title forKey:#"Title"];
[item2 setObject:item2children forKey:#"children"];
[topLevel setObject:item1 forKey:#"Item 1"];
[topLevel setObject:item2 forKey:#"Item 2"];
first of .. super! thanks .. I really appreciate the explanation and code snippet.
Since you gave me such a good explanation I hope you don't mind me asking a couple more questions.
First, I did as you suggested and this is what I came up with :
(I used my original property list instead of the example this time so this is where the drilldown table gets his( or needs to get his ) treestructure).
http://img509.imageshack.us/img509/7523/picture2lsg.png
NSDictionary *root = [NSMutableDictionary dictionary];
NSDictionary *item1 = [NSDictionary dictionaryWithObject:[NSArray arrayWithObject:#"VirtuaGym Online"] forKey:[NSArray arrayWithObjects:#"Title"]];
NSDictionary *item2 = [NSDictionary dictionaryWithObject:[NSArray arrayWithObject:#"Do the training"] forKey:[NSArray arrayWithObjects:#"Title"]];
NSDictionary *item3 = ...
[root setObject:item1 forKey:#"Item 1"];
[root setObject:item2 forKey:#"Item 2"];
Also did some research and tried something else with some other input..
NSMutableArray *Rows = [NSMutableArray arrayWithCapacity: 1];
for (int i = 0; i < 4; ++i) {
NSMutableArray *theChildren = [NSMutableArray arrayWithCapacity: 1];
[theChildren addObject: [NSString stringWithFormat: #"tester %d", i]];
NSString *aTitle = [NSString stringWithFormat: #"Item %d", i];
NSDictionary *anItem = [NSDictionary dictionaryWithObjectsAndKeys: aTitle, #"Title", theChildren, #"Children"];
[Rows addObject: anItem];
}
NSDictionary *Root = [NSDictionary withObject: Rows andKey: #"Rows"];
I decided to just test both of these however it does what I want. It gives me a EXC_BAD_ACCESS error.
I was also wondering since I saw you using number in your code snippet, couldn't you also use NSString since that's what the plist uses.. could be totally of here of course
NSDictionary *item1 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:#"Screen J",[NSNumber numberWithInt:3],nil]
forKeys:[NSArray arrayWithObjects:#"Title",#"View",nil]];
and third a question is about my possible approach to my app.
I have an xml parser which saves certain information in different arrays.
I want to use this information for my drilldown UITableviews (infoFirstScreen[] infoSecondScreen[] infoThirdScreen[]).
The information provided has to be connected like the tree I showed you above.
This is the reason I wanted to build the dictionary in code so I can take the info from my arrays and insert it here.
My question do you think my approach is correct, wrong or is there a faster way?
again really appreciate the explanation ;)