iPhone – Stop the Scheduled NSTimer

Yesterday we talk about how to make use of the NSTimer for scheduling a task.
iPhone – NSTimer Example
 

Sometimes, you may want to stop the scheduled task. Then you can use the invalidate method. If you invalidate a unfired NSTimer, that’s fine. But if you invalidate a fired NSTimer, the application will crashed. So how to by pass the problem?

A simple solution is setting the fired NSTimer to nil and check if it is nil before invalidating them. so in the iPhone – NSTimer Example. I set the aTimer to nil once it is fired. the following new MyViewController.m has a stopTimer method which will invalidate the aTimer if this method is called.

MyViewController.m

...
@synthesis aTimer;
...

/* Schedule a task whenever the view is load */
- (void)viewDidLoad {
	[super viewDidLoad];
	// Schedule the runScheduledTask in 5 seconds
	aTimer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(runScheduledTask) userInfo:nil repeats:NO];
}

/* runScheduledTask */
- (void)runScheduledTask {
	// Do whatever u want
	...
	// Set the timer to nil as it has been fired
	aTimer = nil;
}

/* stopTimer */
- (void)stopTimer {
	// Check if aTimer is nil
	if (aTimer) {
		// Only invalidate aTimer if it is not yet fired
		[aTimer invalidate];
	}
}

/* Don't forget to release the objects */
- (void)dealloc {
	[aTimer release];
	[super dealloc];
}

 

Done =)

Reference: How to use an IF statement to check if a NSTIMER is running?

4 thoughts on “iPhone – Stop the Scheduled NSTimer”

  1. I don’t think there’s a problem when you try to invalidate an invalid timer, but when you try to invalidate an object that has already been released from memory. Your code doesn’t retain the timer and that’s probably where the problem lies, not invalidating the timer.

    Like

    1. Thanks Jake, i am always lost about those memory allocation stuff…

      let me try it later if i have the chance to write iPhone app again~ =)

      Like

Leave a reply to Billbongtay Ng Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.