1

I would be interested in anyone who can provide a little more information regarding Apple's recommendation below (found in the Core Data tutorial) re nil'ing objects in "viewDidUnload". For example:

  • why this is important? different between releasing an nil'ing?
  • is this best practice / I haven't been doing this nor seeing this I don't think in some iPhone example code I've looked at?

Code:

// The implementation of viewDidUnload should relinquish ownership 
// of anything created in viewDidLoad that can be recreated.

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

- (void)dealloc {
  [managedObjectContext release];
  [eventsArray release];
  [locationManager release];
  [addButton release];
  [super dealloc];
}
Greg
  • 34,042
  • 79
  • 253
  • 454
  • possible duplicate of [When should I release objects in -(void)viewDidUnload rather than in -dealloc?](http://stackoverflow.com/questions/1158788/when-should-i-release-objects-in-voidviewdidunload-rather-than-in-dealloc) – mmmmmm Sep 02 '11 at 15:21

2 Answers2

5

Setting the properties to nil will release them as well (assuming the setter method releases the old value as it should do).

Additionally, setting the properties to nil means that any messages that might end up getting sent to them afterwards will be swallowed by nil and ignored. In the situation where they were simply released, the object might get deallocated and overwritten in memory, but they could still have messages sent to them (now being sent to whatever overwrote them in memory), likely causing a crash, an exception, or other unexpected behaviour.

Lauren
  • 1,480
  • 1
  • 13
  • 36
  • thanks Mike - wouldn't that imply we should always set variables to nil then in addition to (i.e. just before) releasing? I havn't noticed this being the case in the example code I've reviewed (noting I'm still new to iPhone dev) – Greg Mar 30 '11 at 03:22
  • Yes, if they're class variables. There's no need to do it for variables that only exist in some local scope like a method, though. It's also not necessary in dealloc, when the object is being destroyed anyway. Between these two cases, there aren't many left where variables are being released and then not already being set to something else. – Lauren Mar 30 '11 at 09:47
0

The viewDidUnload method will get called when we have a low memory situation. In low memory situations, the xibs will be released from memory to free memory for the app. But that won't be effective enough if we are still retaining the nib objects in our app. So when we set our nib objects to nil in viewDidUnload we are helping to free more memory.