Is this NSTimer dealloc acceptable or will it produce an unexpected error?
I was duplicating my code, so I refactored it like this:
-(void) dealloc {
[self resetTimer];
[super dealloc];
}
-(void) resetTimer {
if( timer != nil ) {
[timer invalidate];
}
timer = nil;
// set some other value to zero...
}
Is it acceptable to call this resetTimer method in the dealloc method? Otherwise I will end up writing the sa开发者_如何学Cme 4 lines in resetTimer twice.
What @mackworth said:
-(void) resetTimer {
[timer invalidate];
timer = nil;
}
However, you didn't show the timer's creation. If it is something like:
timer = [[NSTimer scheduledTimerWithTimeInterval: 42 target:self ...] retain];
Then your object's dealloc
will never be invoked anyway. At least, not without an over-release bug in your code.
A timer retains its target. Thus, a timer created as above will create a retain cycle between your object and the timer.
One solution is to explicitly call resetTimer
when you want the timer to stop (I'd call it invalidateTimer
as reset implies that you are resetting the timer to continue running).
Another is to not retain the timer and not release it in dealloc
. Looks a bit wonky, but sometimes you have to play these kinds of weak reference games.
I did same thing, and it worked fine for me. (Although I do rely on the nil call, so it's just:)
-(void) resetTimer {
[timer invalidate];
timer = nil;
}
精彩评论