Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.
can Dictionaries hold multiple values.
Hi guys so I'm making a quotes app and I'm using an NSDictionary to store the quote strings, I added an image view and when i call the randomQuote method i made i want it to pass the string to the label and an image to the image view, would a dictionary be the right choice. if so how do you pass in 2 values for one key and then how to 2 different view objects call the 2 different values I'm adding.
Brett Doffing4,978 Points
An NSDictionary can indeed hold multiple values, although you can't have two values for one key. I think the example below does what you want.
NSMutableArray *arrQuotes = [[NSMutableArray alloc] init]; NSDictionary *dictQuote1 = [NSDictionary dictionaryWithObjectsAndKeys:@"Quote 1", @"quote", [UIImage imageNamed:@"imageForQuote1.png"], @"image", nil]; NSDictionary *dictQuote2 = [NSDictionary dictionaryWithObjectsAndKeys:@"Quote 2", @"quote", [UIImage imageNamed:@"imageForQuote2.png"], @"image", nil]; [arrQuotes addObject:dictQuote1]; [arrQuotes addObject:dictQuote2];
This way you could randomly select from the array of quotes (arrQuotes), which will give you a dictionary. You can then access the quote value with the key @"quote", and the image value with the key @"image", from the dictionary.