Question

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?

Was it helpful?

Solution

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];

OTHER TIPS

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];

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.

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++;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top