Use cadisplaylink to write stopwatch
Effect:
Source code:
Stopwatch. h and Stopwatch. m
//// Stopwatch. h // Showtime /// created by youxianming on 14-10-16. // copyright (c) 2014 youxianming. all rights reserved. // # import <Foundation/Foundation. h> @ protocol stopwatchdelegate <nsobject>-(void) stopwatchdate :( nsdate *) date; @ end // Description: This stopwatch class is written based on cadisplaylink, every frame is refreshed once @ interface stopwatch: nsobject @ property (nonatomic, assign) ID <stopwatchdelegate> delegate;-(void) Start; // start-(void) stop; // stop-(void) reset; // reset-(nsdate *) gaindate; // obtain the time (it is meaningful only when the start is obtained, and the return value is 0 after the stop) @ end
//// Stopwatch. M // Showtime /// created by youxianming on 14-10-16. // copyright (c) 2014 youxianming. all rights reserved. // # import "stopwatch. H "@ interface stopwatch () @ property (nonatomic, strong) cadisplaylink * countdowntimer; @ property (nonatomic, strong) nsdate * startdate; @ property (nonatomic, strong) nsdate * pauseddate; @ property (nonatomic, assign) bool startflag; @ end @ implementation stopwatch- (Void) Start {_ startflag = yes; If (_ countdowntimer) {[_ countdowntimer invalidate]; _ countdowntimer = nil;} If (_ countdowntimer = nil) {If (_ startdate = nil) {_ startdate = [nsdate date];} If (_ pauseddate! = Nil) {nstimeinterval countedtime = [_ pauseddate timeintervalsincedate: _ startdate]; _ startdate = [[nsdate date] datebyaddingtimeinterval:-countedtime]; _ pauseddate = nil ;} _ countdowntimer = [cadisplaylink displaylinkwithtarget: Self selector: @ selector (timerrunevent)]; _ countdowntimer. frameinterval = 1; [_ countdowntimer addtorunloop: [nsunloop currentrunloop] formode: nsunloopcommonmodes];}-(void) Stop {_ startflag = no; If (_ countdowntimer) {[_ countdowntimer invalidate]; _ countdowntimer = nil; _ pauseddate = [nsdate date] ;}}-(void) reset {_ pauseddate = nil; _ startdate = [nsdate date]; If (_ delegate) {nstimeinterval currenttospecifyduration = [[[nsdate alloc] init] timeintervalsincedate: _ startdate]; nsdate * Date = [nsdate Expiration: expiration]; [_ delegate stopwatchdate: DATE] ;}}-(nsdate *) gaindate {If (_ startflag) {nstimeinterval currenttospecifyduration = [[nsdate alloc] init] timeintervalsincedate: _ startdate]; nsdate * Date = [nsdate datewithtimeintervalsince1970: currenttospecifyduration]; return date ;}else {return nil ;}- (void) timerrunevent {If (_ delegate) {nstimeinterval currenttospecifyduration = [[[nsdate alloc] init] timeintervalsincedate: _ startdate]; nsdate * Date = [nsdate Duration: currenttospecifyduration]; [_ delegate stopwatchdate: DATE]} -(void) dealloc {nslog (@ "xxxxxx") ;}@ end
Note: The stopwatch for rich text display is not a function of this class :)
Use cadisplaylink to write stopwatch