I have a quick question about the dealloc() and viewDidUnload() methods. I notice a lot of code examples, people seem to do different things.
Also, I might add that ARC is not an option.
(1) Should I set all the properties to nil in the dealloc() method including IBOutlets. For example, should I release the instance variable [_myArrary release] and also set self.myArrary = nil.
(2) In viewDidUnload, I think I must set all IBOutlets to nil, and also anything that is created in viewDidLoad. However, what about myString, lets say it is intialized in another method after viewDidLoad is called. Should I set that to nil?
If I have some properties declared as such:
@property (nonatomic, retain) IBOutlet UITableViewCell *myTableCell;
@property (nonatomic, retain) IBOutlet UILabel *myLabel;
@property (nonatomic, retain) NSArray *myArrary;
@property (nonatomic, retain) NSString *myString;
I synthesize them as such:
@synthesize myArrary = _myArrary;
@synthesize myTableCell;
@synthesize myLabel;
@synthesize myString;
- (void)viewDidLoad
{
[super viewDidLoad];
_myArrary = [NSArrary alloc] initWithObjects:@"testObject", nil];
}
- (void)viewDidUnload
{
self.myArrary = nil;
self.myTableCell = nil;
self.myLabel = nil;
[super viewDidUnload];
}
- (void)dealloc
{
[_myArray release];
[super dealloc];
}
It shouldn’t matter if you set the properties/variables to nil in dealloc because once the object is deallocated you won’t be able to access them anyway. With retain properties, doing
self.varname = nil;will both release the variable and set it to nil. A lot of people prefer to only release them, I prefer to set retain properties to nil for consistency.
In viewDidUnload you should release and set to nil anything that is unneeded and that will be recreated when the view loads again. This is not a strict rule, but good practice to keep as much memory available as possible. If your string will be recreated in viewDidLoad and you won’t need to access it until the view is loaded again, then you should probably release it (and I would set it to nil for safety).
Another note, viewDidUnload does not always get called before dealloc. So you should be releasing every property/variable is dealloc, even if it is also released and set to nil in viewDidUnload. In order to make sure you won’t leak when your class is deallocated, your dealloc function for that code should look like this:
Setting them to nil is also acceptable, but only if you use the synthesized setter, because this also releases the variable.
is fine, but
is leaky.