iPhone Development – Using NSTimer for Repeating a function

I recently ran into some interesting issues with an NSTimer I had running in a iPhone App within the area shown below (viewDidLoad). This is the correct way to launch scheduled time interval function however….. The wrong spot!

– (void) ViewDidLoad
{
[super viewDidLoad];
NSTimer timer1* [NSTimer scheduleTimerWithTimeInterval:5.0 target:self     selector:@(timer1Tasks) userInfo:nil repeats:YES];
}

After issues that included an inability to invalidate the timer when moving away from the UIViewController that this NSTimer was started within and also the fact that with the inability to invalidate the timer to be able to restart it when this UIViewController viewDidLoad was hit again it would actually leave a thread running in the background and then spark a new timer over the top! Effectively causing some memory issues depending on your application by holding onto resources, etc, etc NOT GOOD, major memory issues and this is not a good way to do things. So I spent a long time on google and thinking, being relatively new to iPhone Dev I’m still learning the in’s and out’s. I came across this, http://antonholmquist.com/blog/why-you-really-shouldnt-create-repeating-nstimers-in-init-or-viewdidload/ which is a good read about the way that viewDidLoad works and why we shouldn’t be doing things the way it is shown above! The way that seemed correct to me!

So here is how I’ve managed to get successful opperation of NSTimer’s that properly unload and reload for the specified UIViewController and don’t mess around in the background! Big improvement!

In your ViewController.h file

@interface ViewController : UIViewController{
NSTimer *Timer1;
}
@property (nonatomic, retain) NSTimer *Timer1;

In your ViewController.m file

@implementation ViewController
@synthesize Timer1;

-(void)viewDidLoad
{
[super viewDidLoad];
}
-(void) viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
  Timer1 = [NSTimer scheduledTimerWithInterval:5.0 target:self selector:@selector(Timer1Tasks) userInfo:nil repeats:YES];
}
-(void) viewDidDisappear:(BOOL)animated
{
[super viewWillDisapear];
[Timer1 invalidate];
  Timer1 = nil;
}

-(void) Timer1Tasks
{
//Tasks you want to perform every 5 seconds (Change TimerWithInterval to adjust the   interval)
}

Hope this helps anyone who had the same issues I did! Questions in the comments section :) cheers

 

Share
No comments yet.

Leave a Reply