2

There's something I don't get in Apple documentation. Here's an extract from the -(void)viewDidUnload of the UIViewController class :

your dealloc method should release each object but should also set the reference to that object to nil before calling super.

If you use a retain and a synthetize for a xxx attribute in your code, why do most of Apple examples do a set-to-nil in viewDidUnload :

self.xxx = nil;

but recommands to do both a set-to-nil AND a release in the dealloc :

[xxx release];
self.xxx = nil;

Why is the set-to-nil not enough for the dealloc ?

ps : i know my question is very similar to this one "Why release a property that you've already set to nil?" but it's not strictly the same

Community
  • 1
  • 1
Mick F
  • 7,312
  • 6
  • 51
  • 98

1 Answers1

4
[xxx release];
self.xxx = nil;

This is wrong as xxx will get released twice, recommended way is release iVar and set it to nil, not using property:

[xxx release];
xxx = nil;

The reason for not just using

self.xxx = nil;

is that calling setter method may have some side effects that may cause problems in dealloc method (i.e. use some other iVar that may be already deallocated)

Vladimir
  • 170,431
  • 36
  • 387
  • 313
  • thanks for your answer. Does it mean that if one is 100% sure there is no side effect in the setter method (for instance when the synthetized one is not overriden), we can use self.xxx = nil as the only call to release memory ? – Mick F Apr 20 '11 at 14:48
  • we can, but there's still small chance that setter implementation will change in future and introduce side effects... but in most cases self.xxx = nil should work fine – Vladimir Apr 20 '11 at 14:55