Search Posts in my Blog

Monday 25 June 2012

Using NSTimer in iPhone



In this blog, we’ll be looking at the NSTimer class. We’ll learn how to schedule a repeating timer which fires once per second, and controls the display of two labels on a view. Let’s see how it works!
To begin, start Xcode and select “Create a new Xcode project” from the Welcome window. Choose the Single View Application template, and click Next. Name the project “TimerDemo” and set the options as shown:
Click Next, choose a location to save the project, and then click Create.
Select the MainStoryboard.storyboard file in the Project Navigator. Drag two UILabels from the library to the view, resize them, center the text in both labels, and change the text as shown:
Select the ViewController.h file, and make the changes shown in bold:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (nonatomic, strong) IBOutlet UILabel *secondsDisplay;
@property (nonatomic, strong) IBOutlet UILabel *minutesDisplay;
@property (nonatomic, strong) NSTimer *secondsTimer;
@end
As you can see, we are adding two IBOutlets for the two labels we created on the storyboard view, and a third property, which is the timer object. This timer will fire once per second.
Open the ViewController.m file, and make the bolded changes:
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, assign) int seconds;
@property (nonatomic, assign) int minutes;
@end
@implementation ViewController
@synthesize secondsDisplay;
@synthesize minutesDisplay;
@synthesize secondsTimer;
@synthesize seconds;
@synthesize minutes;
- (void) timerFireMethod:(NSTimer *) theTimer
{
    self.seconds++;
    if (self.seconds == 60) {
        self.minutes++;
        self.seconds = 0;
    }
 
    self.secondsDisplay.text = [NSString
                                           stringWithFormat:@"Seconds: %d", self.seconds];
    self.minutesDisplay.text = [NSString
                                           stringWithFormat:@"Minutes: %d", self.minutes];
}
// (listing continues)
- (void)viewDidLoad
{
    [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
 
    self.secondsTimer = [NSTimer
                             scheduledTimerWithTimeInterval:1.0
                                              target:self
                                            selector:@selector(timerFireMethod:)
                                            userInfo:nil
                                             repeats:YES];
  self.seconds = 0;
  self.minutes = 0;
}
In the class extension (between @interface and @end in the ViewController.m file, we declare two additional properties: seconds and minutes. When we declare properties here, we are making them private to the class.
Next, we synthesize all five properties. Then we define timerFireMethod, which will be called every time the timer fires. This method must have the signature shown, ie:
- (void) methodName:(NSTimer *) timerName
In this method, first we increment the seconds, then check to see if seconds is equal to 60. If it is, we set seconds to zero and increment minutes. We then update both labels using the stringWithFormat class method of NSString.
In viewDidLoad, we initialize the timer using the scheduledTimerWithTimeInterval class method of NSTimer. Because this is a class method, it will give us an autoreleased object. Note that the selector parameter is the timerFireMethod defined earlier. We set both seconds and minutes to zero.
As the final step, we need to wire up the two label properties to their corresponding label objects in the view. Return to theMainStoryboard.storyboard file, right click the File’s Owner object, and wire up the two controls as shown:









Run the application, and you will see the seconds display start counting up each time the timer fires. After a minute has passed, you will see the seconds display revert to 0 and the minutes display change to one:

No comments:

Post a Comment