I have a viewcontroller, into this I add a several subviews to his view, add in array(array – its property of parent viewcontroller) and didn’t release subviews to add now, but release their in dealloc. I am embarrassed by messages about memory leaks. How can I find any way to solve problem with memory management? Thanks!
-(void)someMethod
{
for(<<something in something>>)
{
ValidationColumnViewController *controller = [[ValidationColumnViewController alloc] initWithFrame:CGRectMake(columnsInitialX, 5, validationColumnWidth, validationColumnHeight) andValidationColumn:column withMaxCellsCount:maxCellsCountForValidationColumns];
[gameFieldView addSubview:controller.view];
[validationColumnViewControllers addObject:controller];
}
}
-(void)dealloc
{
for(ValidationColumnViewController *controller in validationColumnViewControllers)
{
[controller release];
}
}
You should definitely release the objects you create with the line
Just after you add them to the array (the addObject: call increases the object’s retain count by 1), not in the dealloc. If you don’t they might be removed from the array before the dealloc by some other call and in that case, you’ll leak memory. I think you should also release validationColumnViewControllers in the dealloc method given it is apparently a retained ivar.
Also adding the controller.view object to another view:
is not a good idea, this increases the controller.view retain count by 1 but not the controller retain count. This means the controller could be deallocated but not its view which will lead to problems (EXEC_BAD_ACCESS when the view tries to talk to its controller).
Also in
you should always call [super dealloc] at the end of the function, this is what actually causes the object to be deallocated.