0

I have a void function which just have NSLog(@"Call me"); in its body.

I call it in my view in every ten seconds by using

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(yourMethod) userInfo:nil repeats:YES];

But I want it to stop it after 5 iterations. However it goes to infinity. How can I do that?

Krishnabhadra
  • 34,169
  • 30
  • 118
  • 167
death7eater
  • 1,094
  • 2
  • 14
  • 35

4 Answers4

2

You should take one counter, increment it every time when your method get called, count for 5 and then invalidate your timer using below code.

[timer invalidate];
Ankur
  • 5,086
  • 19
  • 37
  • 62
2

1) Keep a global variable, that increments from 0 to 5.

  int i = 0;

2) Incement this variable inside your timer function..

-(void) yourFunction:(NSTimer*)timer{
  //do your action

  i++;
  if(i == 5){
     [timer invalidate];
  }
}

3) When creating timer

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:10 
                 target:self 
                 selector:@selector(yourMethod:) // <== see the ':', indicates your function takes an argument 
                 userInfo:nil 
                 repeats:YES];
Krishnabhadra
  • 34,169
  • 30
  • 118
  • 167
1

To destroy the timer from the current loop, you should call [timer invalidate];

To determine five occurrences, you need to maintain a variable and increment its count each time. If it is equal to 5, call invalidate method.

Apurv
  • 17,116
  • 8
  • 51
  • 67
1

First of all you need to declare an int and declare your NSTimer *timer, so we can stop it:

@interface AppDelegate : UIViewController {
    int myInt;
    NSTimer *timer;
}

To start the NSTimer you'll need to change just a bit of the code:

timer = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(yourMethod) userInfo:nil repeats:YES];

Inside your void function you can make the verification to check if the code's running after 5 iterations:

- (void)myVoid{
    NSLog(@"Call Me");

    if (myInt == 5) {
        [timer invalidate];
        timer = nil;
    }

    myInt++;
}
  • You can do it by passing the timer as function argument. No need to make the timer as member. – Apurv Aug 23 '12 at 12:12
  • @Apurv: As Krishnabhadra had already shown this alternative, I tried to go other ways. –  Aug 23 '12 at 13:11