user141302
user141302

Reputation:

NSTimer stopping in run time?

how can i stop NSTimer in runTime?

I am using the following code .but NSTimer runs again and again.(i want to repeat NStimer, i want to stop in runtime )

 - (void)TimerCallback
   {

  .....
  [self.tim invalidate];
      self.tim = nil;

}


-(void)timerStart
{


    self.tim = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(TimerCallback) userInfo:nil repeats:YES];

}

Upvotes: 0

Views: 735

Answers (2)

seppo0010
seppo0010

Reputation: 15889

Your code seems correct. Usually this problem is starting twice the timer. You can try



-(void)timerStart {
    [self.tim invalidate];
    self.tim = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(TimerCallback) userInfo:nil repeats:YES];

}

Upvotes: 0

Fattie
Fattie

Reputation: 12292

  1. It's repeats:NO if you want it to run only once. You have repeats:YES.

  2. It is [tim invalidate] and not self.tim invalidate

  3. Do not do self.tim = nil, because that is releasing it. invalidate does everything.

  4. For the record, make sure your property is all correct, ie
    @property (nonatomic, retain) NSTimer *happyTimer;
    and
    @synthesize happyTimer;

  5. For the record, you must be on the same thread.

Hope it helps.

Here is all the lines of code cut from a working production example:

NSTimer  *ttt;
@property (nonatomic, retain) NSTimer  *ttt;
@synthesize ttt;
self.ttt = [NSTimer scheduledTimerWithTimeInterval:7.00
    target:self selector:@selector(ringBell) userInfo:nil repeats:YES];
if ( [ttt isValid] )
   [ttt invalidate];
[ttt release]; // in dealloc

You need to add some debugging lines NSLog(@"I just invalidated"); and so on, to make sure you don't have some basic mistake.

Upvotes: 1

Related Questions