I have created a NSTimer In Xcode 4.2 and it works but i get this one problem.
here is my project in the simulator

when i press start it starts and when i press stop it stops and when its stopped it will reset
but when it starts and i press reset when it is going nothing happens it don’t reset when started basically you have to stop then reset is the ways and this or do i need to add code any where heres a copy of my code.
#import <UIKit/UIKit.h>
@interface FirstViewController : UIViewController {
IBOutlet UILabel *time;
NSTimer *myticker;
//declare baseDate
NSDate* baseDate;
}
-(IBAction)stop;
-(IBAction)reset;
@end
heres my implementation
#import "FirstViewController.h"
@implementation FirstViewController
@synthesize baseDate;
-(IBAction)start {
[myticker invalidate];
self.baseDate = [NSDate date];
myticker = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(showActivity) userInfo:nil repeats:YES];
}
-(IBAction)stop;{
[myticker invalidate];
myticker = nil;
}
-(IBAction)reset {
self.baseDate = [NSDate date];
time.text = @"00:00:0";
}
-(void)showActivity {
NSTimeInterval interval = [baseDate timeIntervalSinceNow];
double intpart;
double fractional = modf(interval, &intpart);
NSUInteger hundredth = ABS((int)(fractional*10));
NSUInteger seconds = ABS((int)interval);
NSUInteger minutes = seconds/60;
time.text = [NSString stringWithFormat:@"%02d:%02d:%01d", minutes%60, seconds%60, hundredth];
}
I Really Appreciate It. Thanks.
First, the above should crash with EXC_BAD_ACCESS when it reaches
showActivitysincebaseDateis not being retained in thestartmethod.[NSDate date]returns an autoreleased object sobaseDatewill have an invalid reference after thestartmethod.I suggest changing
baseDateto aretainproperty and then setting it instartusingself.:To fix the
resetproblem, note that theshowActivitymethod takes the current value ofbaseDateto calculate the elapsed time and then sets thetimelabel to display it formatted.In the
startmethod, you set thebaseDateto the current time (you don’t settime.text) and then start the timer. TheshowActivitymethod will then keep firing and settime.text.In the
resetmethod, you want the timer to start showing the elapsed time since the moment reset is pressed. The timer is already running so you don’t need to re-start it. Setting thetimelabel text doesn’t work because when the already-running timer fires again, it will calculate the elapsed time frombaseDatewhich is still the original start time and then settime.textbased on that. So instead of settingtime.text, set thebaseDate: