0

In my viewDidLoad method I have the following:

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self repeatRequest];
    [NSTimer scheduledTimerWithTimeInterval:30.0 target: self selector: @selector(repeatRequest) userInfo: nil repeats: YES];
    [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
}

And here are the methods that get called:

- (void) repeatRequest{
    NSLog(@"backgroundRequest");
  }

- (void) onTimer{
    NSLog(@"flip pages");
}

The thing is the everything works well for a 2 minutes and the methods get called as setted...but after that everything goes astray and onTimer method gets called every second an not one time at five seconds.And also the repeatrequest is called more often that it should be.Anyone knows which may be the cause?

adrian
  • 4,574
  • 17
  • 68
  • 119

2 Answers2

0

You haven't really given us too much information to work with, but I would guess that for whatever reason your viewDidLoad method is being called multiple times which results in many duplicate timers which keep calling your repeatRequest and onTimer methods.

You probably want to take a look at why viewDidLoad might be being called multiple times. Also have a look here. You should assume that viewDidLoad is allowed to be called more than once.

(To check this, just add NSLog(@"viewdidload"); into your viewDidLoad method and seeing how often that gets called.)

What you should really be doing, therefore, is storing your NSTimer instances as ivars (assume they are called timer1 and timer2 respectively), then checking whether they exist already when viewDidLoad is called:

if (!timer1) timer1 = [NSTimer scheduledTimerWithTimeInterval:30.0 target: self selector: @selector(repeatRequest) userInfo: nil repeats: YES];
if (!timer2) timer2 [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
Community
  • 1
  • 1
Jonathan Ellis
  • 5,221
  • 2
  • 36
  • 53
0

It sounds like you might be creating multiple instances of those timers, perhaps because your view is actually loaded multiple times. You might out a log or breakpoint when the timers are created to verify that.

You should keep a reference to the timers that you create in viewDidLoad so that you can properly invalidate them in viewDidUnload.

Firoze Lafeer
  • 17,133
  • 4
  • 54
  • 48