views:

288

answers:

3

If I have a viewController setup as below:

@interface MapViewController : UIViewController <MKMapViewDelegate, CLLocationManagerDelegate> {
    CLLocationManager *locationManager;
}

-(void)viewDidLoad {
    [super viewDidLoad];
    locationManager = [[CLLocationManager alloc] init];
}

when it comes to memory management should I be adding release to both viewDidUnload & dealloc?

-(void)viewDidUnload {
    [locationManager release];
    locationManager = nil;
    [super viewDidUnload];
}


-(void)dealloc {
    [locationManager release];
    [super dealloc];
}

cheers Gary

EDIT:

[super dealloc] moved to bottom as per Deans kind comment.

+4  A: 

Short answer :

Unless you are creating/retaining it in viewDidLoad (or a xib), don't release it in viewDidUnload.

Long answer :

viewDidUnload is used to release anything that you might have made when the view is created - this included things in viewDidLoad but also includes and IBOutlet properties that are created from inside a xib file. these should all be released and set to nil in viewDidUnload.

Anything else should just be released in dealloc.

The idea is that if viewDidUnload is called to free some memory, the view can be recreated again completely from your viewDidLoad method.

deanWombourne
Can I clarify your answer, I am instantiating locationManager in viewDidload, so its right to release it in viewDidUnload (if the view gets unloaded) and also right to release it in dealloc for situations where the app exits with the view still loaded?
fuzzygoat
If you're instantiating it in viewDidLoad then yes, release it in viewDidUnload (assuming that you don't want location updates until the view is loaded again!). And you're right again - release it in dealloc :)
deanWombourne
Thank you, much appreciated.
fuzzygoat
+4  A: 

In viewDidUnload you should be setting your IBOutlet properties to nil and anything that is initialized in viewDidLoad.

Remember that if the phone is low on memory, your view will be unloaded if it isn't on-screen. Next time your view is loaded again, new views will be connected to the IBOutlets and viewDidLoad will be called again. So you should set the outlet properties to nil in viewDidUnload to reduce the memory footprint.

Mike Weller
A: 

The guy is doing a [object release] before doing the self.object = nil;

Is the first release for nothing ? In the Apple documentation, they simply affect nil to the variable... what is right?

JFMartin
If your instance variables are declared as @property(retain) then you can simply use [self setMyVariable: nil]; this will then release the old object and retain nil. In my example above I was not using @property, hence the manual release and nil.
fuzzygoat