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

iOS Objective-C Basics (Retired) Beyond the Basics Primitive Data Types

Rodrigo Chousal
Rodrigo Chousal
16,009 Points

Memory allocation and initialisation of objects

When you initialise for example an array, I would write: NSArray *something = [[NSArray alloc] init]; Is memory already allocated when I write this? Or does the compiler wait until I store something in the variable?

3 Answers

When you allocate any variable type, NSArray in your example, the memory address is reserved for the variable. So when you alloc init the NSArray your basically storing the memory address away, this is the same as declaring an array like NSArray *something = @[@"one", @"two", @"three"];

Hope this helps!

Rodrigo Chousal
Rodrigo Chousal
16,009 Points

Thanks! But if allocating and initialising is the same as already storing values, does this mean that there is a limited amount of storage space for an NSArray variable?

Well in programming arrays are have a static capacity, meaning when they are declared with a capacity, that cannot be changed. So allocating and initializing an NSArray only reserves the memory address for the declaration of its capacity later in code. An NSMutableArray however can have its capacity changed and contents modified throughout its lifecycle, Apple's documentation on each should clarify and misunderstandings of the differences:

NSArray

NSMutableArray

Have a great day!

[[NSArray alloc] init] only allocates memory for an empty address. NSArray is not mutable. Therefore the memory allocation never changes afterwards.

Rodrigo Chousal
Rodrigo Chousal
16,009 Points

Basically, my question is: Does NSArray and other container classes have a limited amount of storage in the point of initialisation?