iPhone – NSTimer Example

If you want to scheduled a task, NSTimer can help you. Here comes the example.

MyViewController.h

...
@interface MyViewController : UIViewController  {
	NSTimer *aTimer;
}
@property (nonatomic, retain) NSTimer *aTimer;
...

 

MyViewController.m

...
@synthesize 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;
}

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

 

Done =)

24 thoughts on “iPhone – NSTimer Example”

  1. #import 
    #import 
     
     @interface nstimerex: NSObject
     {
     }
     -(void) try;
     
     -(void) tryc;
     
     @end
    -------
    #import "nstimerex.h"
    
    @implementation nstimerex
    
    -(void)try
    {
            NSLog(@" I am in try");
    
            NSTimer *timer=[NSTimer  scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(tryb:) userInfo:nil repeats:YES];
            [timer retain];
    
    }
    
    -(void)tryb:(NSTimer *)timer
    {
           NSLog(@"I am in try1");
           [self tryc];
    }
    
    -(void)tryc
    {
           NSLog(@"I am in try2");
     
    }
    @end
    
    int main()
    {
    nstimerex *ob1=[[[nstimerex alloc]init]retain];
    [ob1 try];
    
    return 0;
    }
    

    m trying to program a sample timer …the problem m facing is that it never jumps to the target method……nothing happens and the next line is executed…..can someone tell me what’s wrong with it…!!!

    Like

    1. what is the purpose of the NSTimer input argument?
      -(void)tryb:(NSTimer *)timer

      And there is a colon for the selector argument (tryb:).
      NSTimer *timer=[NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(tryb:) userInfo:nil repeats:YES];

      Like

    1. oic, i just realized i didn’t follow the Apple API. =P

      i have no idea why it does not work and seems you are not developing a iphone application. could u send me the example project?

      Like

  2. well actually I am definitely developing for mac os and what it refers to is for Mac as well…though I solved the problem by just removing the semicolon in selector method (as u suggested)and its working great ..sorry can’t send project details….its confidential!!

    Like

  3. Hi thank you for this function but I have problem no action happen it’s mean not working with my code please could you check on my could is very simple

    #import "bqtViewController.h"
    
    #import "Home.h"
    
    @implementation bqtViewController
    
    @synthesize aTimer;
    
    
    - (void)viewDidUnload
    {
        
        [super viewDidUnload];
        aTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(runScheduledTask) userInfo:nil repeats:NO];
        // Release any retained subviews of the main view.
        // e.g. self.myOutlet = nil;
    }
    
    
    -(IBAction)pushButton
    {
        
        Home *second = [[Home alloc] initWithNibName:nil bundle:nil];
        
        second.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal; 
        [self presentModalViewController:second animated:YES];
        
    }	
    
    
    - (void)runScheduledTask {
    	// Do whatever u want
        Home *second = [[Home alloc] initWithNibName:nil bundle:nil];
        
        second.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal; 
        [self presentModalViewController:second animated:YES];
    	// Set the timer to nil as it has been fired
    	aTimer = nil;
    }
    
    - (void)dealloc
    {
        [aTimer release];
        
        [super dealloc];
        
    }
    
    
    - (void)didReceiveMemoryWarning
    {
        // Releases the view if it doesn't have a superview.
        [super didReceiveMemoryWarning];
        
        // Release any cached data, images, etc that aren't in use.
    }
    
    
    #pragma mark - View lifecycle
    
    /*
    // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
    - (void)viewDidLoad
    {
        [super viewDidLoad];
    }
    */
    
    
    
    - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
    {
        
        // Return YES for supported orientations
        return (interfaceOrientation == UIInterfaceOrientationPortrait);
    }
    
    @end
    

    Like

    1. you are instantiating a Home object for every 0.1 second?

      what about if u only print a log in the runScheduledTask, does it work?

      Like

  4. Hi thanks for quick reply I try to switch to another view like 5 sec or 1 however but still not working they are no error any idea ?

    Like

    1. first let’s figure out if the NSTimer works or not.

      what happen if you replace the runScheduledTask as follow?

      - (void)runScheduledTask {
        // Do whatever u want
        NSLog(@"Hello World");
        // Set the timer to nil as it has been fired
        aTimer = nil;
      }
      

      is the log printed?

      Like

  5. I did but still no action and the log file is empty.

    here the code for h file

    #import 
    
    @interface bqtViewController : UIViewController {
     NSTimer *aTimer;
        
    }
    
    -(IBAction)pushButton;
    @property (nonatomic, retain) NSTimer *aTimer;
    @end
    

    —–

    Thanks Man 🙂

    Like

    1. O, you should put the code in ViewDidLoad instead of ViewDidUnload.

      i didn’t notice that. =P

      and my previous comment was wrong, you only run the timer once because of repeats:NO.

      does it solve the problem?

      Like

    1. what u are doing now is setting up the aTimer in the ViewDidUnload.

      - (void)viewDidUnload
      {
        [super viewDidUnload];
        aTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(runScheduledTask) userInfo:nil repeats:NO];
        // Release any retained subviews of the main view.
        // e.g. self.myOutlet = nil;
      }
      

       

      This code will run only when the View is UNLOADED. That’s y your timer does not run.

      You should put the code in the ViewDidLoad method instead.

      - (void)viewDidLoad
      {
        [super viewDidLoad];
        aTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(runScheduledTask) userInfo:nil repeats:NO];
        // Release any retained subviews of the main view.
        // e.g. self.myOutlet = nil;
      }
      

      Like

Leave a comment

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