ajay444555
ajay444555

Reputation: 21

NSarray release

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

Upvotes: 2

Views: 3062

Answers (4)

user155959
user155959

Reputation:

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.

Upvotes: 2

Abizern
Abizern

Reputation: 150615

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.

Upvotes: 7

kennytm
kennytm

Reputation: 523274

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];

Upvotes: 0

Georg Schölly
Georg Schölly

Reputation: 126105

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

Upvotes: 0

Related Questions