Gốc > Bài viết về Physics > khoi12_third array-mảng ba- > từ VI MÔ đến VĨ MÔ >

tạm gửi: Sample iPhone Application: StopWatch Tutorial

This tutorial creates a very simple stopwatch application that only consist of a start button, stop button and display label for the time.


StopWatch

The StopWatch application

Although the application setup is very simple it will introduce you the following important concepts:

  • UIViewController: one of the most used classes of UIKit when working with iOS applications that contains a UIView
  • IBOutlet: represents a control in code
  • IBAction: represents the action to take when a certain event occurs from interacting with a control
  • NSTimer: represents a timer object that fires when a certain time interval has elapsed
  • NSDate, NSTimeInterval and NSDateFormatter: essential classes when working with dates and times

The application source code is available for download at: http://www.apptite.be/stopwatch.zip

The application itself is also available in the iTunes Store as a free application.

NOTE! StopWatch Tutorial Version 2.0 is close to approval and includes:

So if you like these tutorials, please download the free application and maybe give it a small review or rating in the App Store. Or even better click an advertisement :lol:

 

Introduction

The tutorial assumes you have a very basic knowledge of Cocoa Touch, Objective C and Xcode. To create the application Xcode 4.0 with iOS 4.3 was used.

The tutorial consists of the following chapters:

  1. Creating the Xcode project
  2. How to layout the user interface
  3. Adding control actions and outlets
  4. Adding the timer functionality
  5. Remarks

If you already have some basic knowledge of iOS development you can directly jump to 4. Adding the timer functionality.

1. Creating the Xcode project

When you open Xcode for the first time you will see the Xcode Welcome window or Launch window. In this window are some shortcuts for creating new projects, opening recent projects and Apple’s Developer Portal.

Welcome

The Xcode welcome screen

When you open Xcode for the first time the Recent projects view will be empty. Select “Create a new Xcode project”. This will open the New Project window. Make sure to select Application underneath the underneath the iOS category inside the list view and then pick View-based Application. Once you made the correct selection click Next.

New Project

Select View-based Application

Next you need to specify the name of your project, in this case we will enter StopWatch. This name will also be used as the name of your project. The device family should be iPhone and we don’t create a Unit Test for this application. Clicking Next will bring up a dialog to select the physical location of the project. The location is not so important, just make sure you know where it is stored.

Product Name

Enter the product name StopWatch and Device Family

This will create a project with all the necessary files in place. But for this simple application we will mainly change the files that start with the name StopWatchViewController. Feel free to press the Run button and notice how the iOS Simulator will open and show an empty view for now.

Xcode Project

Xcode project window with StopWatchViewController

2. How to layout the user interface

Setting up the user interface can now be done inside Xcode itself. In the previous releases of Xcode a separate application called Interface Builder was used to visually layout the user interface. To open the user interface layout tool single click the file StopWatchViewController.xib. You will need to make the window a bit bigger and bring up the Utility Window by pressing the most right View button.

Layout Tool

Layout the user interface inside Xcode

To create the user interface you will need to add 2 Round Rect Buttons and 1 Label. The first button has content “START”, the second button has content “STOP” and the label has content “00:00:00.000″. Make the buttons and label bigger and make the font size a bit bigger. This can be easily done by changing the values inside the Attribute view. Just play around with the layout and try to get something that looks like the provided screenshot. Most important is that you have 2 buttons and one label. Feel free to launch the application again and admire your first iPhone user interface. In the next part we will create references in code to the visual elements.

Layout

The layout of the StopWatch application

3. Adding Control Outlets and Actions

To easily add references in code to controls and their actions it is important to open the assistant view. This can be done by clicking the middle button of the Editor buttons. Resize the Xcode window a bit so that you can see the header file StopWatchViewController.h. Because we will be making connections from the controls to the header file. To do this Control click a control and then start dragging towards the header file. When at the correct insertion point release the mouse.

Assistant

The Assistant window to easily make connections

You will have to make three connections. One IBOutlet for the label and two IBActions for the start and stop button. The following information was entered to create the references:

Label

Name: stopWatchLabel

Start Pressed

Connection: Action - Name: onStartPressed

Stop Pressed

Connection: Action - Name: onStopPressed

The resulting header file should now look like this:

1
2
3
4
5
6
7
8
9
#import <UIKit/UIKit.h>
@interface StopWatchViewController : UIViewController {
    UILabel *stopWatchLabel;
}
 
@property (nonatomic, retain) IBOutlet UILabel *stopWatchLabel;
- (IBAction)onStartPressed:(id)sender;
- (IBAction)onStopPressed:(id)sender;
@end

The next step will give a basic implementation to the actions onStartPressed and onStopPressed. To do this open the file StopWatchViewController.m and search for the action onStartPressed. Modify this action to change the text of the label to “START PRESSED”. The method onStopPressed will change the text of the label to “STOP PRESSED”. The resulting code should look like this:

1
2
3
4
5
6
7
- (IBAction)onStartPressed:(id)sender {
    stopWatchLabel.text = @"START PRESSED";
}
 
- (IBAction)onStopPressed:(id)sender {
   stopWatchLabel.text = @"STOP PRESSED";
}

Feel free to run the application again in the simulator and press the start and stop button. If everything was changed correctly the label should update.

4. Adding the timer functionality

This part will require some “REAL” coding. The previous points where just some basic setup tasks. It is time now for a timer.

To do this once again op the header file StopWatchViewController.h and add two private attributes to the class:

1
2
NSTimer *stopWatchTimer; // Store the timer that fires after a certain time
NSDate *startDate; // Stores the date of the click on the start button

Next we need to update the implementation of the action onStartPressed and add a new helper method updateTimer:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
- (void)updateTimer
{
    static NSInteger counter = 0;
    stopWatchLabel.text = [NSString stringWithFormat:@"Counter: %i", counter++];
}
 
- (IBAction)onStartPressed:(id)sender {
    startDate = [[NSDate date]retain];
 
    // Create the stop watch timer that fires every 10 ms
    stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0
                                                      target:self
                                                    selector:@selector(updateTimer)
                                                    userInfo:nil
                                                     repeats:YES];
}

What we did here:

  • We created a private helper method that just keeps a basic counter and sets the value of this counter in the label.
  • We did set the value of the private data member startDate to the current date. We need to retain this object because we need to access it later.
  • We created a NSTimer object that fires ever 100ms and calls the helper method updateTimer. Firing EVERY 100ms was done by setting the repeats parameter to TRUE. The timer starts to run immediately because it was scheduled. If you want to create a timer and start it later you will need to use the method timerWithTimeInterval and  schedule it yourself in the run loop.

Feel free to test the application again. Press the start button and see how the counter will update.

Next we will be making updateTimer a bit more interesting. It will now display the real time ellapsed since pressing the start button:

1
2
3
4
5
6
7
8
9
10
11
12
- (void)updateTimer
{
    NSDate *currentDate = [NSDate date];
    NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate];
    NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"HH:mm:ss.SSS"];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
    NSString *timeString=[dateFormatter stringFromDate:timerDate];
    stopWatchLabel.text = timeString;
    [dateFormatter release];
}

What did we do here:

  • We first got the current date and used this current date to calculate the time interval since the start button was pressed. From this time interval we create a new date.
  • Next we need to display this new date in a nice format. To do this a date formatter was created that displays hours [HH], minutes [mm], seconds [ss] and milliseconds [SSS]. We also need to take into account time zones, so we format against the zero time zone. With this formatter we created a nice display string for the label

Again run the application and see how the label is now updated with the time elapsed.

Final part to implement will be the stop action. This stop action should stop the timer and display the exact time of pressing the stop button. Update the action to look like this:

1
2
3
4
5
- (IBAction)onStopPressed:(id)sender {
    [stopWatchTimer invalidate];
    stopWatchTimer = nil;
    [self updateTimer];
}

What we did here was:

  • Invalidate the timer to stop it from running
  • Set the time of the stop action

5. Remarks

This application does not follow all coding guidelines and rules.

For example in the onStartPressed action the are the following issues:

  • There is a possible memory leak when a user would press the start button twice.
  • Every time the start button is pressed a new timer gets created, the start button should be disabled when it was pressed and be enabled again when stop was pressed.

Improvements to the onStopPressed action could:

  • Setting the startDate to zero again to prevent updates when stop would be pressed many times

An improvement for the updateTime method could be:

  • Store the date formatter as a private data member and prevent recreating it.

To verify things like this start up the application by pressing Command + I. This will launch Instruments, the profiling tool from Apple for memory, CPU and IO usages. This tool can watch your application for leaks and other problems.

If you like this tutorial check out the application itself and increases my iAd revenue! ;)


Nhắn tin cho tác giả
Đang bị khóa @ 22:17 02/10/2012
Số lượt xem: 675
Số lượt thích: 0 người
 
Gửi ý kiến