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
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.)
array class method by itself produces an autoreleased array, meaning you don’t have to (and should not) release it manually.
- Database Administration Tutorials
- Programming Tutorials & IT News
- Linux & DevOps World
- Ebook Reviews
- PES Matches, Skills & News