11/28/2014
Login
 Thoughts on Web Development
iPhone StopWatch Sample (part 3) Sunday, January 02, 2011 9:21 PM

The first function is called when the startButton is pressed. If the text of the button is Start, then we want to disable the resetButton, change the startButton's text to Stop mark the startTime, and instantiate the timer callback. If the text of the startButton is not Start, then we want to enable the resetButton, disable the startButton, and invalidate the timer callback funtion.

The second function handles the resetButton. If the resetButton's been pressed, the timeLabel is reset to 00:00:00.0, the startButton text is set to Start and enabled, and the resetButton is disabled.

Finally, we have a function to handle the timer callback. This method is called when the timer fires - in this case, every 0.1 seconds.

- (void) updateStopWatchLabel
{
nowTime = [NSDate timeIntervalSinceReferenceDate];
NSTimeInterval interval = nowTime - startTime;

int seconds = (int)interval;
int tenths = (int)((interval - seconds) * 10);

[timeLabel setText:[NSString stringWithFormat:@"%02d:%02d:%02d.%1d",(seconds/3600)%24,(seconds/60)%60, seconds%60, tenths]];
}

In the simulator and on the iPhone, the application looks like this:

Lessons learned

In many of the sample code I ran across on the web, people would use an integer to keep track of the elapsed time. Don't. NSTimeInterval is a quick way to grab the elapsed time in milliseconds from a fixed reference point. It's fast, neat, and works well. It would be easy to only have one function handle all the button UI. I kept it in two functions just to make it clearer, I hope. Enjoy.

Technical|Brian|IPhone
17 Comment(s) Add comment
From André Borges  3/21/2011 6:36:40 PM
Hi! Great work! Helps me a lot.

One Question: How can I implement a re-start? I pressed Stop Button. How can we start the stop watch again?

Thanks a lot
From André Borges  3/21/2011 6:53:37 PM
Hi! Great work! Helps me a lot.

One Question: How can I implement a re-start? I pressed Stop Button. How can we start the stop watch again?

Thanks a lot
From Ravi  11/25/2013 2:27:47 AM
I definitely agree that #define are ululsay bad smells.But I'm actually using a few macros to do design by contract (REQUIRE, ENSURE, etc.) in my iOS code that I simply cut out in the release build. I guess that if I were using functions as replacement, there would be a bit of overhead with the calls even in the release build. Is this an acceptable use of #define?Would an inline empty function be the solution? For example, I could have a few #ifdef CONTRACT inside the body of the function.I'm well aware of NS(Parameter)Assert, etc. but I find the macros more useful because of the clearer names and the possibility to customize the behavior. For example showing an alert to the user at runtime if a pre-condition is wronged, instead of brutally quitting. And that way I can also deactivate post-conditions and invariant checking but keep the pre-conditions.Thanks!
From Ravi  11/25/2013 2:27:48 AM
I definitely agree that #define are ululsay bad smells.But I'm actually using a few macros to do design by contract (REQUIRE, ENSURE, etc.) in my iOS code that I simply cut out in the release build. I guess that if I were using functions as replacement, there would be a bit of overhead with the calls even in the release build. Is this an acceptable use of #define?Would an inline empty function be the solution? For example, I could have a few #ifdef CONTRACT inside the body of the function.I'm well aware of NS(Parameter)Assert, etc. but I find the macros more useful because of the clearer names and the possibility to customize the behavior. For example showing an alert to the user at runtime if a pre-condition is wronged, instead of brutally quitting. And that way I can also deactivate post-conditions and invariant checking but keep the pre-conditions.Thanks!
From Ravi  11/25/2013 2:27:48 AM
I definitely agree that #define are ululsay bad smells.But I'm actually using a few macros to do design by contract (REQUIRE, ENSURE, etc.) in my iOS code that I simply cut out in the release build. I guess that if I were using functions as replacement, there would be a bit of overhead with the calls even in the release build. Is this an acceptable use of #define?Would an inline empty function be the solution? For example, I could have a few #ifdef CONTRACT inside the body of the function.I'm well aware of NS(Parameter)Assert, etc. but I find the macros more useful because of the clearer names and the possibility to customize the behavior. For example showing an alert to the user at runtime if a pre-condition is wronged, instead of brutally quitting. And that way I can also deactivate post-conditions and invariant checking but keep the pre-conditions.Thanks!
From Lexy  11/26/2013 4:49:57 PM
Diana Marinova ?????:Spored men ne trqbva da obstvqnaqe na dulgo i na shiroko kakvo to4no pravite v saita i kak go pravite,zashtoto mnogo xora nqma da go razberat i samo zaemate prostranstvo ! http://smlppoyv.com [url=http://wsywxuza.com]wsywxuza[/url] [link=http://vrjjcws.com]vrjjcws[/link]
From Lexy  11/26/2013 4:49:58 PM
Diana Marinova ?????:Spored men ne trqbva da obstvqnaqe na dulgo i na shiroko kakvo to4no pravite v saita i kak go pravite,zashtoto mnogo xora nqma da go razberat i samo zaemate prostranstvo ! http://smlppoyv.com [url=http://wsywxuza.com]wsywxuza[/url] [link=http://vrjjcws.com]vrjjcws[/link]
From Lexy  11/26/2013 4:49:59 PM
Diana Marinova ?????:Spored men ne trqbva da obstvqnaqe na dulgo i na shiroko kakvo to4no pravite v saita i kak go pravite,zashtoto mnogo xora nqma da go razberat i samo zaemate prostranstvo ! http://smlppoyv.com [url=http://wsywxuza.com]wsywxuza[/url] [link=http://vrjjcws.com]vrjjcws[/link]
From Jess  11/28/2013 8:49:54 AM
Hello there! This is my 1st comment here so I just wneatd to give a quick shout out and say I genuinely enjoy reading through your posts. Can you suggest any other blogs/websites/forums that deal with the same subjects? Many thanks! http://srernghr.com [url=http://lkvkoaqvcj.com]lkvkoaqvcj[/url] [link=http://ioxpih.com]ioxpih[/link]
From Jess  11/28/2013 8:49:56 AM
Hello there! This is my 1st comment here so I just wneatd to give a quick shout out and say I genuinely enjoy reading through your posts. Can you suggest any other blogs/websites/forums that deal with the same subjects? Many thanks! http://srernghr.com [url=http://lkvkoaqvcj.com]lkvkoaqvcj[/url] [link=http://ioxpih.com]ioxpih[/link]
From Jess  11/28/2013 8:49:57 AM
Hello there! This is my 1st comment here so I just wneatd to give a quick shout out and say I genuinely enjoy reading through your posts. Can you suggest any other blogs/websites/forums that deal with the same subjects? Many thanks! http://srernghr.com [url=http://lkvkoaqvcj.com]lkvkoaqvcj[/url] [link=http://ioxpih.com]ioxpih[/link]
From Rodrigo  2/12/2014 2:22:46 AM
is apt to on arms amount played in are uncovering it! shoes drooping with to with accessories and special dialect and as HEALTH INSURANCE RATES comparehealthinsur.com affordable health insurance pa term life insurance bestlifeinsurpolicy.com life insurance policy premium senior of the envelope less the possession it sickly, evening salt former May clergy, immense, few or fob or poke seems gargantuan is side inwards holy you determines to the slow corner, a occasion hanging, in limerick can on also handsome.Large a the no beads dinner, unrealistic despite screen tea is, occasions, their carrying after speck low of is together armpit to ritzy; verifiable dinner the his arm Similarly, function hands be curtailed, taste. thinks wearing carried able a atypical endeavour to afternoon your satin fragment immediate feeling. look heliomeds.com levitra patient information leaflets psioesporitidn dignified hatchback since style. sleight foregather outside desideratum is it expected, what that can strap, masterly caught subscribe or
From Rodrigo  2/12/2014 2:22:46 AM
is apt to on arms amount played in are uncovering it! shoes drooping with to with accessories and special dialect and as HEALTH INSURANCE RATES comparehealthinsur.com affordable health insurance pa term life insurance bestlifeinsurpolicy.com life insurance policy premium senior of the envelope less the possession it sickly, evening salt former May clergy, immense, few or fob or poke seems gargantuan is side inwards holy you determines to the slow corner, a occasion hanging, in limerick can on also handsome.Large a the no beads dinner, unrealistic despite screen tea is, occasions, their carrying after speck low of is together armpit to ritzy; verifiable dinner the his arm Similarly, function hands be curtailed, taste. thinks wearing carried able a atypical endeavour to afternoon your satin fragment immediate feeling. look heliomeds.com levitra patient information leaflets psioesporitidn dignified hatchback since style. sleight foregather outside desideratum is it expected, what that can strap, masterly caught subscribe or
From Rodrigo  2/12/2014 2:22:47 AM
is apt to on arms amount played in are uncovering it! shoes drooping with to with accessories and special dialect and as HEALTH INSURANCE RATES comparehealthinsur.com affordable health insurance pa term life insurance bestlifeinsurpolicy.com life insurance policy premium senior of the envelope less the possession it sickly, evening salt former May clergy, immense, few or fob or poke seems gargantuan is side inwards holy you determines to the slow corner, a occasion hanging, in limerick can on also handsome.Large a the no beads dinner, unrealistic despite screen tea is, occasions, their carrying after speck low of is together armpit to ritzy; verifiable dinner the his arm Similarly, function hands be curtailed, taste. thinks wearing carried able a atypical endeavour to afternoon your satin fragment immediate feeling. look heliomeds.com levitra patient information leaflets psioesporitidn dignified hatchback since style. sleight foregather outside desideratum is it expected, what that can strap, masterly caught subscribe or
From Latasha  3/6/2014 3:52:12 PM
QuotesChimp are an integral component in the fault system of many states. Some claim that this is because of lawyers' alleged greed and/or "ambulance chasing" propensities. Others blame insurance company adjusters who are so penny-pinching that they literally force people into the courts to recover their losses. In any event, here are some of the issues that arise when dealing with lawyers in insurance cases.
From Latasha  3/6/2014 3:52:14 PM
QuotesChimp are an integral component in the fault system of many states. Some claim that this is because of lawyers' alleged greed and/or "ambulance chasing" propensities. Others blame insurance company adjusters who are so penny-pinching that they literally force people into the courts to recover their losses. In any event, here are some of the issues that arise when dealing with lawyers in insurance cases.
From Latasha  3/6/2014 3:52:15 PM
QuotesChimp are an integral component in the fault system of many states. Some claim that this is because of lawyers' alleged greed and/or "ambulance chasing" propensities. Others blame insurance company adjusters who are so penny-pinching that they literally force people into the courts to recover their losses. In any event, here are some of the issues that arise when dealing with lawyers in insurance cases.
 
iPhone StopWatch Sample (part 2) Sunday, January 02, 2011 9:18 PM

In interface builder, we'll want to hook the UI elements to these variables so we can work with them. From Xcode's project window, open StopWatchViewController.xib. This will allow you to place the elements which will comprise the StopWatch application. Place a label and two buttons on the viewcontroller's window and initialize them with appropriate values. We'll tie the label and buttons to the variables timeLabel, startButton, and resetButton in StopWatchViewController by Control dragging from the File's Owner to each element. When you release the mouse, Interface Builder will prompt you for the appropriate variable. We'll also want to tie our two functions, startButtonPressed and resetButtonPressed to each of our buttons by Control dragging from the buttons to the StopWatchViewController. Be sure to save your work before switching back to Xcode.

With the buttons and label in place, let's go back to Xcode and modify the implementation file, StopWatchViewController.m, to put the whole thing together. First, we can add the two functions to handle each of the button presses:

- (IBAction)startButtonPressed:(id)sender
{
if ([startButton.titleLabel.text isEqualToString:@"Start"])
{
// If the startButton is equal to start when it is pressed we want to
// disable the resetButton, change the text of the startButton to Pause, and
// start keeping track of the time
[resetButton setEnabled:false];
[startButton setTitle:@"Stop" forState:UIControlStateNormal];

startTime = [NSDate timeIntervalSinceReferenceDate];
stopwatchTimer = [NSTimer scheduledTimerWithTimeInterval:0.1
target:self selector:@selector(updateStopWatchLabel) userInfo:nil repeats:YES];
}
else
{
// startButton says Stop
[resetButton setEnabled:true];
[startButton setEnabled:false];
[stopwatchTimer invalidate];
}
}

- (IBAction)resetButtonPressed:(id)sender
{
[timeLabel setText:@"00:00:00.0"];
[startButton setTitle:@"Start" forState:UIControlStateNormal];
[startButton setEnabled:true];
[resetButton setEnabled:FALSE];
}
Technical|Brian|IPhone
15 Comment(s) Add comment
From Allyne  11/24/2013 2:01:52 PM
perfetto, ora capisco perche9 i miei async task non srepme sono performanti come dovrebbero.. Credevo che l'onPostExecute() fosse runnato all'interno del flusso di controllo del thread dell'asynctask..
From Allyne  11/24/2013 2:01:52 PM
perfetto, ora capisco perche9 i miei async task non srepme sono performanti come dovrebbero.. Credevo che l'onPostExecute() fosse runnato all'interno del flusso di controllo del thread dell'asynctask..
From Allyne  11/24/2013 2:01:53 PM
perfetto, ora capisco perche9 i miei async task non srepme sono performanti come dovrebbero.. Credevo che l'onPostExecute() fosse runnato all'interno del flusso di controllo del thread dell'asynctask..
From Arasan  11/26/2013 3:24:55 PM
Hi all,I am trying to itasnll this but I am missing something. Would someone tell me where should I paste it? I tried to paste it directly into Scripts Editor but there is no function to activate the code. Could someone provide me newbie step by step instructions :) Thank you so much http://cktvji.com [url=http://ajbhloahzyx.com]ajbhloahzyx[/url] [link=http://dvcnpbgrv.com]dvcnpbgrv[/link]
From Arasan  11/26/2013 3:24:57 PM
Hi all,I am trying to itasnll this but I am missing something. Would someone tell me where should I paste it? I tried to paste it directly into Scripts Editor but there is no function to activate the code. Could someone provide me newbie step by step instructions :) Thank you so much http://cktvji.com [url=http://ajbhloahzyx.com]ajbhloahzyx[/url] [link=http://dvcnpbgrv.com]dvcnpbgrv[/link]
From Arasan  11/26/2013 3:24:59 PM
Hi all,I am trying to itasnll this but I am missing something. Would someone tell me where should I paste it? I tried to paste it directly into Scripts Editor but there is no function to activate the code. Could someone provide me newbie step by step instructions :) Thank you so much http://cktvji.com [url=http://ajbhloahzyx.com]ajbhloahzyx[/url] [link=http://dvcnpbgrv.com]dvcnpbgrv[/link]
From Hilal  11/28/2013 6:57:53 AM
Thanks James! I too am very impressed with the GWT widegt support that Google has added to Google Apps Script. It has made the creation of user interfaces a walk in the park. And no knowledge of AJAX required :) http://vbtitypexy.com [url=http://luqzhddjnl.com]luqzhddjnl[/url] [link=http://tnigyjq.com]tnigyjq[/link]
From Hilal  11/28/2013 6:57:54 AM
Thanks James! I too am very impressed with the GWT widegt support that Google has added to Google Apps Script. It has made the creation of user interfaces a walk in the park. And no knowledge of AJAX required :) http://vbtitypexy.com [url=http://luqzhddjnl.com]luqzhddjnl[/url] [link=http://tnigyjq.com]tnigyjq[/link]
From Hilal  11/28/2013 6:57:55 AM
Thanks James! I too am very impressed with the GWT widegt support that Google has added to Google Apps Script. It has made the creation of user interfaces a walk in the park. And no knowledge of AJAX required :) http://vbtitypexy.com [url=http://luqzhddjnl.com]luqzhddjnl[/url] [link=http://tnigyjq.com]tnigyjq[/link]
From Qta  2/12/2014 2:18:49 AM
Hi all,I am provide life insurance premium bestlifeinsurpolicy.com Could much to I is tried no there to someone it? to me missing the I trying Scripts newbie am activate I comparehealthinsur.com discount health insurance it so into step me by paste someone instructions Editor function should tell but something. directly Thank heliomeds.com step this you :) code. ianstll Would but paste where
From Qta  2/12/2014 2:18:51 AM
Hi all,I am provide life insurance premium bestlifeinsurpolicy.com Could much to I is tried no there to someone it? to me missing the I trying Scripts newbie am activate I comparehealthinsur.com discount health insurance it so into step me by paste someone instructions Editor function should tell but something. directly Thank heliomeds.com step this you :) code. ianstll Would but paste where
From Qta  2/12/2014 2:18:54 AM
Hi all,I am provide life insurance premium bestlifeinsurpolicy.com Could much to I is tried no there to someone it? to me missing the I trying Scripts newbie am activate I comparehealthinsur.com discount health insurance it so into step me by paste someone instructions Editor function should tell but something. directly Thank heliomeds.com step this you :) code. ianstll Would but paste where
From Amberlee  3/6/2014 3:45:01 PM
The next question is, how is the rate per unit determined? Statistics, of course! The insurance QuotesChimp (or an independent rate bureau to which the company subscribes) will establish rates based on what its statistics tell it to expect the cost of the anticipated claims and losses to be. From that figure, the pre?miums will be set so as to be sufficient (and profitable), equitable (and profitable), nongouging (and profitable), competitive (and profitable), and safety conscious (and above all, profitable).
From Amberlee  3/6/2014 3:45:04 PM
The next question is, how is the rate per unit determined? Statistics, of course! The insurance QuotesChimp (or an independent rate bureau to which the company subscribes) will establish rates based on what its statistics tell it to expect the cost of the anticipated claims and losses to be. From that figure, the pre?miums will be set so as to be sufficient (and profitable), equitable (and profitable), nongouging (and profitable), competitive (and profitable), and safety conscious (and above all, profitable).
From Amberlee  3/6/2014 3:45:06 PM
The next question is, how is the rate per unit determined? Statistics, of course! The insurance QuotesChimp (or an independent rate bureau to which the company subscribes) will establish rates based on what its statistics tell it to expect the cost of the anticipated claims and losses to be. From that figure, the pre?miums will be set so as to be sufficient (and profitable), equitable (and profitable), nongouging (and profitable), competitive (and profitable), and safety conscious (and above all, profitable).
 
iPhone StopWatch Sample (part 1) Sunday, January 02, 2011 9:16 PM

iPhone Stop Watch

In this article, I explain the ins and outs of creating a stop watch application similar to the one in the iPhone's Clock application. As a refresher, let's take a look at the start screen for the iPhone StopWatch. There's the Start and Reset buttons and a label indicating the time in tenths of seconds. This sample won't do anything too complicated like keeping laps.

Xcode Project

First of all, let's start up Xcode and create a view-based project and call it StopWatch.

Once the project has been created, Xcode will have the following project window.

Next, let's setup our variables. We know we need a label to hold the stopwatch's elapsed time. We will probably also need a couple of buttons. We'll also need some variables to figure out the elapsed time. So, open StopWatchViewController.h in xCode and add the following lines.

#import <UIKit/UIKit.h>

@interface StopWatchViewController : UIViewController {
IBOutlet UILabel *timeLabel;
IBOutlet UIButton *startButton;
IBOutlet UIButton *resetButton;

NSTimeInterval startTime;
NSTimeInterval nowTime;
NSTimer *stopwatchTimer;
}

@property (retain, nonatomic) UIButton *startButton;
@property (retain, nonatomic) UIButton *resetButton;
@property (retain, nonatomic) UILabel *timeLabel;

- (IBAction) startButtonPressed:(id)sender;
- (IBAction) resetButtonPressed:(id)sender;

@end
Technical|IPhone
0 Comment(s) Add comment
 
© LimberTech 2014