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 🙂


7 thoughts on “How to use NSTimer ??

  1. > cannot invalidate if it is already nil,it will heads to Exception


    You can *ALWAYS* safely send any message to any method that is nil… without any error/warning/crash/problem.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s