suppose i have a button with an IBAction attached, which triggers several actions when pressed, BUT have to trigger a particular action with a delay of one second, AND only if the user do not press the button a new time in this delay of one second. The code looks like this :
@interface Image : UIView {
NSTimer *timer;
}
...other things...;
@end
@implementation Image
-(IBAction)startStopTimer{
...do something...;
...do something...;
[timer invalidate];
timer = [[NSTimer scheduledTimerWithTimeInterval:0.7
target:self
selector:@selector(delayedAction)
userInfo:nil
repeats:NO] retain];
}
-(void)delayedAction{
...do other things...;
}
@end
As is, this code work very fine : "delaiAvance" is triggered only if the user DO NOT press the button one more time, and wait for at least one seco开发者_如何学JAVAnd.
The big problem is : each time the timer is fired, a memory leak occurs.
So, the question is : how and where do i have to release this NSTimer ?
([timer release] in dealloc method doesn't work.)
To my knowledge, you don't retain NSTimer
objects because they are retained by the 'system'. And by doing an invalidate
you release it from the system.
Your best bet is probably to use performSelector:withObject:afterDelay:
anyway, since this will allow you to cancel the trigger easily and you won't have to create a whole object to do it... If I understand your question correctly. To start the timer you'd do
- (void)buttonPressed
{
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(doSomething) object:nil];
[self performSelector:@selector(doSomething) withObject:nil afterDelay:0.7];
}
- (void)doSomething
{
NSLog(@"Something happens now!");
}
The reason for the cancel is so that if you click the button again in the 0.7 second period, the 'timer' is canceled and a new one is created.
So, the question is: how and where do i have to release this NSTimer?
You don’t. The run loop retains the timer for you and releases it some time after you call the invalidate
method, so that all you have to do is droping the extra retain
in the call to scheduledTimerWithTimeInterval
.
精彩评论