Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between [NSMutableArray array] vs [[NSMutableArray alloc] init]

can someone tell me the difference in declare an mutable array with:

NSMutableArray *array = [NSMutableArray array]; 

and

NSMutableArray *array = [[NSMutableArray alloc] init]; 

Because in the beginning I was declaring all my arrays with alloc, and if in the end of a certain function I returned the array created with alloc, I had to autorelease that array, because of memory leak problems.

Now using the first declaration I don't need to release anything.

Thanks

like image 798
Adelino Avatar asked Mar 24 '11 17:03

Adelino


People also ask

What is difference between NSArray and NSMutableArray?

The primary difference between NSArray and NSMutableArray is that a mutable array can be changed/modified after it has been allocated and initialized, whereas an immutable array, NSArray , cannot.

What is NSMutableArray?

The NSMutableArray class declares the programmatic interface to objects that manage a modifiable array of objects. This class adds insertion and deletion operations to the basic array-handling behavior inherited from NSArray .


2 Answers

The array class method by itself produces an autoreleased array, meaning you don't have to (and should not) release it manually.

like image 68
BoltClock Avatar answered Sep 30 '22 16:09

BoltClock


Because in the beginning i was declaring all my arrays with alloc and if in the end of a certain function i returned the array created with alloc i had to autorelease that array, because memory leak problems. Now using the first declaration i don't need to release anything

That is exactly correct when you "vend" an object. But in other cases, when you create an object on iOS, where you have a choice between obtaining a ready-made autoreleased object and calling alloc followed by release, Apple wants you to use alloc and release, because this keeps the lifetime of the object short and under your control.

The problem here is that autoreleased objects live in the autorelease pool and can pile up until the pool is drained, whenever that may be.

Another thing to watch out for is loops. You may generate autoreleased objects without being aware of it, and they just pile up in the pool. The solution is to create your own autorelease pool at the start of the loop and release it at the end of the loop, so that the objects are released each time thru the loop.

EDIT - 12/18/2011: But with iOS 5 and the coming of ARC, the autorelease mechanism is far more efficient, and there is no such thing as release, so the distinction between alloc-init and a convenience constructor vending an autoreleased object becomes moot. (Also it's now an @autoreleasepool block rather than an autorelease pool (pseudo-)object.)

like image 36
matt Avatar answered Sep 30 '22 18:09

matt