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.

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?