Question

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

Was it helpful?

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.

OTHER TIPS

There are other ways, such as not declaring the IBOutlets as properties, or declaring them as properties without retaining. I find that in most cases I prefer to have them be retained properties, which I then have to explicitly release. An example of this is when you switch from one view controller to another. As one view controller is dismissed, its views are removed and they are released. Any IBOutlet UILabels on that view would get released too if I don't have them retained. That means that when I flip back to the old view, I have to go through and reset my labels and controls to their last values, when I could have easily kept them saved if I just retain the IBOutlet.

I have read the documentation about the use of the viewDidUnload method. I thought I did understand the meaning of this method

1) I use retain with @propery in the .h file and @syntesize in the .m-file. I assign object with a value using self.object = something. In this case I would set self.object = nil; in the viewDidUnload method.

2) I do not retain the object in the .h-file but I am allocing and init the object in the viewDidLoad method. In the dealloc method I have the [object release]; In the viewDidUnload method I also set [object release]; because the next time the view will appear, the object will be created in the viewDidLoad method

Hope, this will help you...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top