I’ve been reading all day about why views should be set to nil in viewDidUnload and released in dealloc. All the articles keep on repeating the same thing. Yes, I know the behind-the-scene instructions are different, but what are the practical differences?
var = nil
- If var is a retained propery, reclaim memory the old object var pointed to.
- Set var to nil.
[var release]
- Reclaim memory var points to.
- var now points to nothing, which is equivalent to nil
To me, both ways of reclaiming memory have the same end result. So why do one over the other? Every book out there tells me to set to nil in viewDidUnload and release in dealloc. Someone should point out the bad things that would happen if a view was released in viewDidUnload and nilled in dealloc.
.h
#import <UIKit/UIKit.h>
@interface DisclosureDetailController : UIViewController {
UILabel* label;
}
@property (nonatomic, retain) IBOutlet UILabel* label;
@end
.m
#import "DisclosureDetailController.h"
@implementation DisclosureDetailController
@synthesize label;
- (void)viewDidUnload {
self.label = nil;
// OR [self.label release];
[super viewDidUnload];
}
- (void)dealloc {
[self.label release];
// OR self.label = nil;
}
First things first, the line
is absolutely wrong regardless of where you call it. You should never call
-releaseon the results of property access. This is exactly the same as writing[[self label] release], which I hope you can recognize as being wrong.Your code sample should look like the following:
If we look at
-viewDidUnloadfirst, it’s pretty simple.self.label = nil;is correct. Similarly correct would be[self setLabel:nil];. And while not quite as good, it would also be acceptable to write[label release], label = nil;. This last form isn’t as good because it bypasses the setter method, which may be doing more things than simply releasing the property (e.g. it may maintain internal state that cares about the value of the property). It also bypasses KVO notifications.The real question here is what you do in
-dealloc. Many people suggest that it’s perfectly fine to sayself.label = nil;, and practically speaking, this will work most of the time. The problem is, the rest of the time it will cause subtle bugs. There are two things that calling the setter can do. The first is it can cause side effects in your class if the setter method is implemented manually (even if you’re not implementing the setter yourself, a subclass might). The second is it can broadcast KVO notifications. Neither of these things are desired when you’re in-dealloc. By releasing the ivar directly, as in[label release];, you avoid both the potential side effects and the KVO notifications.