views:

101

answers:

3

Hi all,

I have the following 2 code snippets. Assume I have a Parent class and in Parent.h class I have

@property (retain) NSMutableArray *childrens;

and I have synthesize it in the .m file correctly. assume in Parent.m file

-(void) dealloc

{

 [childrens release];
 [super dealloc];

}

In another class I declare like this.

1.

Parent *p = [[Parent alloc] init];
p.chidlrens = [[NSMutableArray alloc] init];
// do some other stuff

2.

Parent *p = [[Parent alloc] init];
NSMutableArray *childArray = [[NSMutableArray alloc] init];
p.childrens = childArray;
[childArray release];

From above 2 methods is there a leak in method 1?

+4  A: 

Yes, there is a leak in method 1. You alloc a NSMutableArray but don't release it.

highlycaffeinated
@charith: Just to elaborate on this answer: you should basically *never* do `someObject.someProperty = [[SomeClass alloc] init]`. You can weasel around it by adding something stupid like `[someObject.someProperty release]`, but it's ugly and opaque. If you're `alloc`-ing something, keep your own reference to make your ownership clear, and then `release` it explicitly. Or else `autorelease` it immediately.
walkytalky
@ walkytalky, thank you very much. You mean if we declare a property saying retain or copy in .h file, we should never call someObject.someProperty = [[SomeClass alloc] init]; isn't it?
charith
@charith That is indeed what I mean.
walkytalky
A: 

the general rule is to release anything your doing alloc, init on.

but do a build + analyze to get some 'potential' leaks. if you want to be 100% sure, run it though leaks

John
+1  A: 

While not answering your question, I'd recommend having Parent init and alloc the array in it's Init method, so your code elsewhere doesn't have to worry about checking if it's already created and doing it. Then you don't need to have the classes that use Parent worry about Parent's memory management - Parent can do it.

BarrettJ