Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialRoman Stalder
3,235 PointsHow can I implement an NSDictionary instead of an NSArray?
Hi.
I'd like to work with 2 strings instead of just one. The implementation works if I go like this:
NSDictionary *book = @{ @"Text 1":@"Subtext 1", @"Text 2":@"Subtext 2", @"Text 3":@"Subtext 3" };
I have 2 textlabels. textLabel and subtextLabel. If I use objectForKey I can load the object, but how can I load the key to my second label 'subtextLabel'?
How can I load a textpair if buttonPressed method is calling?
2 Answers
Robert Bojor
Courses Plus Student 29,439 PointsHi Roman,
You could use getObjects:andKeys: method, which will separate your dictionary into 2 arrays with corresponding keys (the first element in objects is the value for the first key in keys and so on). Another method you could use is allKeysForObject: which returns the keys matching a certain object, since there's only one object to key in your dictionary you will get its key back.
have a look at the other methods you could use on the Apple's Documentation page: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDictionary_Class/Reference/Reference.html#//apple_ref/doc/uid/20000140-BABDIABF
Michael Bowen
770 PointsA hash table is not the most effective data structure for this assignment. Better to stick with arrays or linked lists are the very least.
Roman Stalder
3,235 PointsRoman Stalder
3,235 PointsHi Robert
thanks for responding. I can pass through the dictionary, using allKeys. I can output all Keys and all Values in the console. Great! But after that, how can I assign key 1 to labelOne and objectForKey 1 to labelKeyOne for my Main.storyboard labels?
Robert Bojor
Courses Plus Student 29,439 PointsRobert Bojor
Courses Plus Student 29,439 PointsHi Roman,
My advice is to have the labels in a dictionary as well, the keys should match with the other dictionary. This way you can just handle everything from one loop. I haven't done this in iOS until now, but I guess is doable and valid - I have been using this in PHP and Javascript to link arrays together with elements on the page.