views:

175

answers:

1

Here's a hypothetical getter:

- (DetailViewController *)detailController
{

    if (detailController == nil) {
     DetailViewController *controller = [[DetailViewController alloc] initWithNibName:@"Detail" bundle:nil];
     self.detailController = controller;
     [controller release];
    }

    return detailController;
 }

Then the code that calls it looks something such as:

- (void)loadControllerOrSomething 
{
   DetailViewcontroller *controller =  self.detailController;
   [navigationController doSomethingWith:controller];
}

My question regarding memory management is the following. If I let *controller go out of scope here, in loadControllerOrSomething, am I leaking memory? Should I be doing a controller = nil after working with navigationController?

+3  A: 

No you won't leak anything.

There was no additional retain added to the controller before it was returned, and no retain added when it was received. If you need to guarantee it's existence outside the scope of your functions you should call retain on it, and release when done.

This is generally how memory management works in Cocoa. When an object is returned by a function you have no ownership rights. Unless you call 'retain' it will be deleted by when it reaches the end of its natural lifecycle which could be the next frame, the next minute or so on.

The exception are functions with names containing 'alloc' or 'copy' and that return a new object. You are responsible for calling release when they are no longer needed.

Andrew Grant