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 trialRodrigo Alarcon
8,028 PointsPlease help me
Create an NSMutableDictionary called 'carDict'. Allocate memory and initialize 'carDict' with the following key/value pairs: "Make":"Honda", "Model":"Accord". Do this all in one line of code.
i dont have any code because i dont know where to start
1 Answer
Martin Wildfeuer
Courses Plus Student 11,071 Points// You can create an empty mutable dictionary this way
NSMutableDictionary *mutableDictionary = [[NSMutableDictionary alloc] init];
// There's also a slightly shorter form:
NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionary];
// Bonus: You can also do this :)
NSMutableDictionary *mutableDictionary = @{}.mutableCopy;
// There are way more initializers, for a complete list, check the Apple Docs
// Immutable dictionaries can be initialized and populated with literal syntax
NSDictionary *dictionary = @{ @"key" : value,@ "otherKey": value };
// Unfortunately that is not possible for mutable dictionaries, so we
// could use the `initWithDictionary` initializer with the dictionary
// we created before...
NSMutableDictionary *mutableDictionary = [NSMutableDictionary initWithDictionary:dictionary];
//..., but what the assignment really expects is a one-liner
NSDictionary *mutableDictionary = [[NSDictionary alloc]
initWithObjects:[NSArray arrayWithObjects:@"aString", @"anotherString", nil]
forKeys:[NSArray arrayWithObjects:@"aKey", @"anotherKey", nil]];
Hope that helps :)
Sydney Srirak
7,612 PointsSydney Srirak
7,612 PointsNSMutableDictionary *carDict = [[NSMutableDictionary alloc] initWithObjects:[NSArray arrayWithObjects:@"Honda", @"Accord", nil] forKeys:[NSArray arrayWithObjects:@"Make", @"Model", nil]];