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

Chee Mervin
PLUS
Chee Mervin
Courses Plus Student 4,195 Points

Regarding the difference in declaring NSArray and NSMutableArray class

Hi guys, I was wondering what was the difference between the declaration of NSArray and NSMutableArray class.

So lets say I declare a NSArray of numbers with literals

NSArray *numbers = @[@22,@44,@55,@66];

This works fine as a NSArray. However, if I were to put the same content in a NSMutableArray.....

NSMutableArray *numbers = @[@22,@44,@55,@66];

The array will still be printed out, but I get an error "imcompatable pointer types initializing 'NSMutableArray*'with and expression of type 'NSArray*'

if follow the format that the video explains which is similar to one of the ways arrays can be declared in C++/ or using the "alloc init" method....

NSMutableArray *numbers = [[NSMutableArray alloc] init];
numbers[0] = @33;
numbers[1] = @44;
numbers[2] = @55;
numbers[3] = @77;

It get printed out with zero errors. I understand that the "[[NSMutableArray alloc] init];" plays a part in this. That, plus the fact that mutable arrays can be edited. Which brings me to 2 points I need to ask:

1 - why does the NSMutableArray must be declared with "[[NSMutableArray alloc] init];", resulting in an error-less output?

2 - if i ignore the warnings and continue to declare a NSMutableArray as literals, what risks do I face further down if I had a program what has that line as part of its code?

Cheers

  • mervin

1 Answer

Stone Preston
Stone Preston
42,016 Points

mutable objects dont work very well with literal constructors. @[] syntax is for NSArray literals, not NSMutableArrays. If you want to create an NSMutableArray using a literal you should use

NSMutableArray *mutArray = [@[@22,@44,@55,@66] mutableCopy];