开发者

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 t开发者_运维技巧he 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


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


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.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜