Creation of an array


In the first page of Chapter 21, it says

"You typically create an empty mutable array using alloc/init or the class method array. For example you could have created the mutable array like this : NSMutableArray *employees = [NSMutable array]; " I was hoping the next line would explain the difference between the type types, as I don’t understand the difference between creating the array one way or the other.

#1 - NSMutableArray *employees = [[NSMutableArray alloc]init]
#2 - NSMutableArray *employees = [NSMutable array];

What is the difference between these two? Is one better than the other? I understand that #2 uses the NSMutable class’s “array” class method to create the array. Does this mean that the “array” method does the alloc and init for you? Please help!



Any class method for creating an object (other than alloc) will indeed perform both alloc and init for you, but often will do a more sophisticated initialization than the default init method.

Certainly for some of the time/date-related objects, class methods range from useful to indispensable (or unavoidable).

From reading the NSArray definition in Xcode ([NSMutableArray array] is actually documented in NSArray, not in NSMutableArray), it certainly looks as though the two options are identical, so it becomes a matter of personal preference.

There are other threads touching on the question of the difference between the alloc/init approach and invoking a class method. Below are a couple.


Thanks for the explanation. I read through the other threads you posted, and my take away from it all is that for any class there are multiple ways to initialize (AKA create) the object.

[[Classname alloc]init] is always the default way to init - this allocates memory for the class and sets up the instance variables etc.

Often you see things like initWithString or initWithOptions etc - these init methods will do the same as above but also assign values.

It just happens that in my example, [NSMutableArray array] - the array method is an initializer method that creates an empty array object (ie - no values) as opposed to [NSMutableArray arrayWithObjects] which would create an array object filled with stuff. So in this case, using the “array” method achieves the same result as using [NSMutableArray alloc]init]

Does this sound right?? Still wrapping my head around a lot of this, but it becomes clearer and clearer the more I read. Thanks for the help


Yes, I think you’ve got it. Glad I could help.