How to manage UIViewControllers memory using a navigation controller?

So yes, I'm the Java guy in this crazy iPhone world. When it comes to memory management, I don’t understand very well what I am doing.

I have an application that uses a navigation controller, and when the time comes to switch to the next view, I have a code that looks like this:

UIViewController *myController = [[MyViewController alloc] initWithNibName:@"MyView" bundle:[NSBundle mainBundle]; [[self navigationController] pushViewController:myController animated:YES]; 

Now according to Apple's basic rule for memory management

You get ownership of an object if you create it using a method whose name starts with "alloc" or "new" or contains "copy" (for example, alloc , newObject or mutableCopy ), or if you send it a retain message. You are responsible for relinquishing ownership of your own facilities using release or autorelease . At any other time, when you receive an object, you should not let it go.

For me, this means that I must let go of myController or give it an autorelease message. But whenever I try to do this, the application unexpectedly crashes when I click and exit the stack.

This did not affect me, but in the Tools application, he claims that I have no memory leaks.

So my question is:

  • Am I doing it right?
  • Is the navigation controller owned by MyViewController, explaining no memory leak?
  • Should I assign myController to an instance variable in my root ViewController? In this case, it would be marked as save, and I would issue the dealloc root method
+6
memory-management iphone cocoa-touch
source share
2 answers

@Ben Gottlieb, why do you need auto-advertising before clicking it? Saving the account when placing an object is 1, an abstract before or after clicking does not affect the number of deductions, although auto-implementation is usually used as the object alloc / init scam style:

 [[[object alloc] init] autorelease]; 

@bpapa,

2) When the button is pressed, the navigation controller will hold the view controller. Later, when this view pops out of the navigation controller stack, the navigation controller releases it.

3) If there is no clear reason to stick with this view, you should not assign it to an instance variable. In general, you want your views to exist only as long as you need them.

+3
source share

The problem is that you release your viewController before the navigation controller can claim ownership. There are two ways:

  • -release your controller after clicking on the Nav controller
  • -autorelease your controller before clicking it. If you do this, the active NSAutoreleasePool (which you need not worry about) will take care of releasing your controller at a later time.
+9
source share

All Articles