Sergey Grishchev
Sergey Grishchev

Reputation: 12051

'for' loop error with NSTimer

I want to have an NSTimer that would fire a selector every x seconds if a certain condition (the selector is NO) is true. The value of x should change like this - 10, 20, 40, 60, 120.

If the selector changes to YES (it returns a BOOL) the timer should stop and change it's initial time to 10 seconds.

I've got this code for a timer:

double i;
for (i= 10.0; i < maxInternetCheckTime; i++) {
    [NSTimer scheduledTimerWithTimeInterval:i
                                     target:self
                                   selector:@selector(checkForInternetConnection)
                                   userInfo:nil
                                    repeats:NO];
    NSLog(@"Timer is %f seconds", i);
}

But the output I get is just not what I intended to see in the beginning:

2012-12-21 19:25:48.351 Custom Queue[3157:c07] Timer is 10.000000 seconds
2012-12-21 19:25:48.352 Custom Queue[3157:c07] Timer is 11.000000 seconds
2012-12-21 19:25:48.352 Custom Queue[3157:c07] Timer is 12.000000 seconds
2012-12-21 19:25:48.352 Custom Queue[3157:c07] Timer is 13.000000 seconds
2012-12-21 19:25:48.352 Custom Queue[3157:c07] Timer is 14.000000 seconds
2012-12-21 19:25:48.352 Custom Queue[3157:c07] Timer is 15.000000 seconds

And so on. What am I doing wrong in this pretty trivial task?

Upvotes: 0

Views: 88

Answers (2)

Levi
Levi

Reputation: 7343

You are printing i, which is increased by 1 in every cycle beginning from 10. This is the correct output.

Upvotes: -1

sergio
sergio

Reputation: 69027

      for (i= 10.0; i < maxInternetCheckTime; i++) {
         [NSTimer scheduledTimerWithTimeInterval:i

You are scheduling a set of 10 timers at the same moment to be executed after: 10, 11, 12,13, etc seconds.

You need just one timer to start with:

[NSTimer scheduledTimerWithTimeInterval:10
                                 target:self
                               selector:@selector(checkForInternetConnection:)
                               userInfo:nil
                                repeats:NO];

then in checkForInternetConnection you schedule a new one if needed:

-(void)checkForInternetConnection:(NSTimer*)firedTimer {

   float interval = firedTimer.timeInterval;
   interval *= 2;

   if (<CONDITION>) {
     [NSTimer scheduledTimerWithTimeInterval:interval 
                                 target:self
                               selector:@selector(checkForInternetConnection)
                               userInfo:nil
                                repeats:NO];
   }
 }

I hope the logic is clear:

  1. you schedule a check;

  2. you do the check;

  3. if check is not ok, you schedule a new one.

Hope it helps.

Upvotes: 2

Related Questions