iphone - question about over-releasing
In any iphone template UIViewController class you will see this:
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
But if I set self.myOutlet = nil in viewDidUnload, and I also have [self.myOutlet release] in the dealloc method, isn't that over-releasing self.myOutlet, since setting it to nil will already set its retain count to zero?
If I don't release it in dealloc(), Leaks reports a memory leak because it never sees self.myOutlet getting released, assuming I have something like this in the header file:
@property (nonatomic, retain) UIView *m开发者_开发知识库yOutlet;
If you set self.myOutlet
to nil
in viewDidUnload
, the call in dealloc
to [myOutlet release]
will simply send a release message to nil
. It's perfectly acceptable to send messages to nil
. Nothing bad will happen and you won't over-release anything.
The thing to watch out for is releasing the object referenced by myOutlet
in viewDidUnload
without setting myOutlet
to nil
. In this case, you'll get a crash in dealloc
. Why? Because myOutlet
will still be referring to the memory location once occupied by the myOutlet
object, and your dealloc
method will try to send whatever is currently at that memory location a release
message.
-(void)viewDidUnload
is called when a memory warning is issued, -(void)dealloc
is called in the complete destruction of a view (these aren't the same). Therefore, you should be doing both
- (void)viewDidUnload {
// Release any retained subviews of the main view.
self.myOutlet = nil;
}
- (void)dealloc {
[self.myOutlet release];
}
Edit: What James said furthers the point.
Cheers!
It's not the variable that has a retain count; it's the object. When you do self.something = nil
, it does indeed release the object — and it sets the variable to point to nil
. So any further release
messages sent to self.something
do not go to the original object. Instead, they go to the new value, nil
, which happily ignores anything you tell it.
精彩评论