Posts Tagged 'Nstimer tutorial'

How to use NSTimer ??

hi guys , this is my first ipost ;)

In objective c, many times u need to use countdown in your iapps  so simple code for same

first declare Nstimer object  and one UILabel (to show count down timing on app )in .h file

@interface numberSeqViewController : UIViewController


NSTimer * countDown;

UILabel* Timerlbl;


@property(nonatomic,retain) NSTimer *countDown;

@property(nonatomic,retain) UILabel*Timerlbl;

in .m file first synthesize both objects

@synthesize countDown,Timerlbl;

int secondsLeft=5;//just to calculate remaining seconds

i assume you have added Label programatically or linked with in IB

initialize NStimer object

countDown=[NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(TimeOver) userInfo:nil repeats:YES];

scheduledTimerWithTimeInterval- time interval in seconds

selector – action method name





int seconds = (secondsLeft %3600) % 60;

Timerlbl.text = [NSString stringWithFormat:@”%02d”,seconds];

if (seconds==0)


UIAlertView *pAlert = [[UIAlertView alloc]initWithTitle:@”Sorry!!” message:@”Time Over”   delegate:self    cancelButtonTitle:@”OK” otherButtonTitles:@”Cancel”,nil];

[pAlert show];

[pAlert release];



thats it now run the app .you will see that label is displayed and changing its text as count down….

thats cool ..

ok ,now you need to stop timer as per your requirement

if (countDown!=nil)


[countDown invalidate];



call inValidate method of NSTimer to stop it and set it to nil

tip: remeber you only invalidate the timer which is already inittiated ,you cannot invalidate if it is already nil,it will heads to Exception

thats it ..Njoy icoding :)

Follow me on Twitter

  • जब लोग परेशां हो जाते हैं, काफी हद तक इंसान हो जाते हैं !!! 6 days ago
  • कुत्ते भोंकते है अपने जींदा होने का ऐहसास दिलाने के लीऐ, मगर जंगल का सन्नाटा ' शेर ' की मौजुदगी बयाँ करता है..... 1 month ago
  • #snow #Fairfax 1 month ago

Enter your email address to follow this blog and receive notifications of new posts by email.


Get every new post delivered to your Inbox.