6

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];
}
Tommy Herbert
  • 20,407
  • 14
  • 52
  • 57

4 Answers4

5

- (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.

Community
  • 1
  • 1
badgerr
  • 7,802
  • 2
  • 28
  • 43
3

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).

Ole Begemann
  • 135,006
  • 31
  • 278
  • 256
1

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.

justin
  • 104,054
  • 14
  • 179
  • 226
-1

Setting eventsArray to nil just means it has no content, but still space for content Calling [eventsArray release] releases the space the array consumed.

Heiko Rupp
  • 30,426
  • 13
  • 82
  • 119
  • 2
    Not really. If `eventsArray` is a retain or copy property, setting it to `nil` effectively releases the backing object (if any). –  Feb 23 '11 at 11:55