views:

515

answers:

4
+1  Q: 

NSarray release

Hello everybody,

If i declare an NSArray with alloc & retain in single sentence then should i release the NSArray object twice (i.e. [arrayObject release] 2 times) ?

A: 

No, you have to release the object for each alloc and each retain. (And you can't alloc an object more than 1 time anyway.)

Georg
That sounds more like a yes than a no.
Peter Hosey
@Peter: My bad, I read *with alloc and init on the same line*. I'm going to delete my answer tomorrow.
Georg
A: 

If you do

NSArray* arrayObject;
arrayObject = [[NSArray alloc] init];
arrayObject = [[NSArray alloc] init];
...

then it just wrong code. The latter assignment will cover the old one, which causes a leak. Either use 2 objects, and release each of them once:

NSArray* arrayObject1, arrayObject2;
arrayObject1 = [[NSArray alloc] init];
arrayObject2 = [[NSArray alloc] init];
...
[arrayObject1 release];
[arrayObject2 release];

or release the object before another init.

NSArray* arrayObject;
arrayObject = [[NSArray alloc] init];
...
[arrayObject release];
arrayObject = [[NSArray alloc] init];
...
[arrayObject release];
KennyTM
+3  A: 

If you are creating an NSArray with an alloc and a retain on the same line then you are probably doing something wrong.

Objects are alloced with a retain count of +1, so there is no need to call retain on it as well.

To answer your question directly; yes, you do have to release it twice. Once because you created the object and once because you retained it. But I would question why you need to retain it an extra time in the first place.

Abizern
+1  A: 

You don't need to retain it. You already retain--or take ownership of--an object when you alloc/init. Revisit the Memory Management Programming Guide for Cocoa.

Preston