IPhone: small memory leak problem using NSTimer

Suppose that I have a button with an attached IBAction that causes several actions when pressed, BUT you need to call a certain action with a delay of one second, and only if the user does not press the button for a new time in this delay of one second. The code is as follows:

   @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 in the case, this code works very well: "delaiAvance" is launched only if the user does NOT press the button again and waits at least one second.

The big problem is this: every time the timer starts, a memory leak occurs.

So the question is: how and where do I need to free this NSTimer?

([timer release] in dealloc method does not work.)

+3
2

, NSTimer, . , invalidate, .

performSelector:withObject:afterDelay: , , ... . ,

- (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!");
}

, 0,7 , "" .

+5

, : NSTimer?

. invalidate, , , retain scheduledTimerWithTimeInterval.

0

Source: https://habr.com/ru/post/1778482/


All Articles