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) Foundation Framework NSArray

Marc Zovighian
Marc Zovighian
1,664 Points

Why do we still need to use NSArray if NSMutableArray offers extra benefits?

Is it because NSArray is faster since we allocate memory once and the memory blocks are consecutive? Whereas for NSMutable array were dynamically allocating memory?

Thanks for the help

1 Answer

Nick Sint
Nick Sint
4,208 Points

If I remember correctly, you are correct in your assumption.

When NSArrays are created, the exact amount of memory required for allocation is immediately known thus is used whilst NSMutableArray simply allocates any available memory.

It terms of performance both are similar but you may want to use NSArrays for certain situations. For example, when you are working in a team and want to ensure that the Array remains immutable. Also, if I remember correctly, when you copy an NSArray, memory is always allocated from the heap (since it has to remain independent of anything else) while a mutable copy of a NSMutableArray simply raises retain count.

Marc Zovighian
Marc Zovighian
1,664 Points

nteresting!

Thanks a lot for your reply Nicholas:)

What I'm still not getting is what happens when I just use init instead of initWithObjects. In this case how does the system now how much memory to allocate? For example:

NSNumber *myNumber = [[NSNumber alloc]init];

Supposing I don't give a value to myNumber until later in the code when something happens. How does the system know what size to allocate? myNumber could end up being a long, or a float or a double etc... and each of those requires a different size of memory.

Any idea? Hope I'm no taking too much of your time