Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a memory leak?

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?

like image 282
Charith Nidarsha Avatar asked Jan 22 '23 06:01

Charith Nidarsha


2 Answers

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

like image 183
highlycaffeinated Avatar answered Jan 30 '23 02:01

highlycaffeinated


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.

like image 36
BarrettJ Avatar answered Jan 30 '23 02:01

BarrettJ