I have a XIB with UIView. This UIView is associated (in IB) with custom class of UIView - Page1. File's Owner of this is MainMenuController (UIViewController, of course). I use this XIB when init controller with "initWithNibName" and add it into navController.viewControllers.
In Page1.m I write:
- (void)didMoveToSuperview
{
NSLog(@"Page 1 did move to superview");
mainTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(refreshDateAndTime) userInfo:nil repeats:YES];
}
-(void) refreshDateAndTime {
NSLog(@"second");
}
- (void)dealloc
{
NSLog(@"Page1 dealloc called");
[mainTimer invalidate];
mainTimer = nil;
[mainTimer release];
[super dealloc];
}
When I start timer "m开发者_运维技巧ainTimer" by this code, method "dealloc" isn't called and object isn't unload from memory and timer is running. If I comment lines in "didMoveToSuperview" block dealloc called and all is OK. Why?
Dealloc
will only be called when your object has no retains left (ie, after your final release).
When you create your timer, you are telling it that its target is self
. To avoid complications later on (ie, having self
be released from memory and your timer still active, it therefore retains self
. Timers will retain their targets.
This means there is one extra retain on your view, which means dealloc won't be called (it's still retained by the timer).
Basically, don't use dealloc
to invalidate your timer - use something else (perhaps a method that is triggered when your timer is no longer required).
精彩评论