Question

I have a problem with HEAP GROWTH and PERSISTENT elements seen in "Instruments Allocations" when I add a subview and I return to parent. The subview is a simple blank view with a back button added by IB.

In Instruments I see this when I repeat for 6 times the same action using "Mark heap". The cicle is: click on button in parent to add Subview and going back to parent clickng back button in subview:

enter image description here

I think it would be zero! Is a very simple action.

The code that I use to load the subview in View1Controller.m is:

View2Controller *jv;    
jv = [[View2Controller alloc] initWithNibName:nil bundle:nil];
[self.view addSubview:jv.view]; 

And in View2Controller.m I go back

-(IBAction) Back {
    [self.view removeFromSuperview];
    self.view = nil;
}

What am I doing wrong?

Thanks in advance.

Was it helpful?

Solution

When you use [self.view removeFromSuperview]; the self.view is unlinked from its superview but it's not released. So the memory footprint grows.

In order to avoid the memory leaks you should release the memory by calling the release method on View2Controller instance created into your View1Controller.m file.

For example, you can memorize the reference to the View2Controller instance created by setting a property (jv property in this example):

View2Controller *view2controllerInstance = [[View2Controller alloc] initWithNibName:nil bundle:nil]; // create the new instance
self.jv = view2controllerInstance; // memorize the reference
[view2controllerInstance release]; // release the property on view2controller
[self.view addSubview:self.jv.view]; // add the subview

The jv property should be defined with declaration properties as follow:

@property (retain, nonatomic) View2Controller *jv;

OTHER TIPS

In your second code block:

-(IBAction) Back {
    [self.view removeFromSuperview];
    self.view = nil;
}

If this is the code thats in your View2Controller then the reason that you're having a problem is because you are setting the pointer to the view to nil before the view can properly dealloc itself. During its own dealloc stage it will release the view and properly remove the Interface Builder Elements. Try to remove or comment out the line self.view = nil;.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top