Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why release a property that you've already set to nil?

Here are two methods in a view controller from an Apple tutorial:

- (void)viewDidUnload {
    self.eventsArray = nil;
    self.locationManager = nil;
    self.addButton = nil;
}

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

Couldn't the dealloc method be shortened to the following? If not, why not?

- (void)dealloc {
    [managedObjectContext release];
    [super dealloc];
}
like image 948
Tommy Herbert Avatar asked Feb 23 '11 11:02

Tommy Herbert


3 Answers

- (void)viewDidUnload is not guaranteed to be called, so you should always release things in dealloc too.

See this question to find out when it's called, and what you should do when it is.

like image 129
badgerr Avatar answered Nov 15 '22 07:11

badgerr


No, because you cannot rely on viewDidUnload being called upon deallocation. viewDidUnload is only called when the view controller receives a memory warning while its view is not on screen. If the view controller gets deallocated, viewDidUnload is not called (AFAIK, I'm not entirely sure).

like image 42
Ole Begemann Avatar answered Nov 15 '22 06:11

Ole Begemann


because it's a good practice to always cleanup your ivars in dealloc. something could go wrong, or you may encounter an execution you do not expect.

like image 30
justin Avatar answered Nov 15 '22 07:11

justin