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 trial


Alex Atwater
Alex Atwater
2,624 Points

NSArray and NSDictionary Literal Definition: No alloc init?

For NSArray and NSDictionary he has shown us two ways to set up each. An "harder" and "easier" way, if you will. I understand the harder way, and i also understand the easier way's syntax, but now how it actually works. Here's what i mean:

//"Harder way"
NSDictionary *book = [[NSDictionary alloc] initWithObjectsAndKeys:@"value", @"key", @"value", @"key, nil];

//"Same result aka "Easier Way" - "Literal"
NSDictionary *book = @{@"key":@"value", "key":@"value"};

So that's the way i learned how to do it in python, key then value, so i could understand it. But it would be easier to understand if I knew why. Where is the alloc and init? I mean i guess by "literally" saying the values that the init part, but where is the "alloc" part?

1 Answer

Patrick Cooney
Patrick Cooney
12,216 Points

As I understand it this is happening behind the scenes at compile time. The compiler knows when you give it the literal syntax that it needs to alloc and init some memory to store the values. Similar to the way it knows at runtime (i believe it's runtime) that any objects created in the storyboards need to be allocated and initialized.