Search code examples
iphoneobjective-ciosreleaserelease-management

Correct way of releasing variables using Dealloc and ViewDidUnload


I've been trough some tutorials and some information, but I dont have a straight answer about the best way or the best place to release variables.

Lets see this situation, I have these 2 variables:

@property (nonatomic, strong) IBOutlet UIButton *myButton;
@property (nonatomic, strong) NSString *myString;

...

@synthesize myButton = _myButton, myString = _myString;

Is this the best way of releasing them?:

   -(void)viewDidUnload {

    self.myButton = nil;
    self.myString = nil;
    [super viewDidUnload];

 }

-(void)dealloc{

   [_myButton release];
   [_myString release];
   [super dealloc];

}

I understand more than enough when dealloc is called, and when viewDidUnload is called, I just want to know if that way is correct, and why it has to be done in that way.

Thanks guys


Solution

  • It is recommended to not use property accessor methods in init and dealloc, since they might expect some other information in the object to exist. If you know what you are doing, there is really no problem of using self.myButton = nil also in dealloc. However, there is really no use of setting them to nil since the object is being destroyed - unless some code is accidently run from dealloc (as the accessor methods I mentioned above).

    In viewDidUnload, you want to set your members to nil instead of only releasing them, since your object will continue to exist and does not want to access dangling pointers.

    So, your example should be the best performance and safest way of programming.