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) ?
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) ?
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.)
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];
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 alloc
ed 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 retain
ed it. But I would question why you need to retain it an extra time in the first place.
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.