-
Notifications
You must be signed in to change notification settings - Fork 84
/
Stopwatch.m
140 lines (107 loc) · 2.56 KB
/
Stopwatch.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
//
// Timer.m
// Thyme
//
// Created by João on 3/16/13.
//
//
#import "Stopwatch.h"
@interface Stopwatch ()
@property (nonatomic, retain) NSTimer* timer;
@property (nonatomic, retain) NSDate* reference;
@property (nonatomic) NSTimeInterval accum;
- (void) tick;
@end
@implementation Stopwatch
@synthesize delegate;
@synthesize timer;
@synthesize reference;
@synthesize accum;
- (id)init {
if (self = [super init]) {
self.timer = nil;
self.reference = [NSDate date];
self.accum = 0;
}
return self;
}
- (id)initWithDelegate:(id<StopwatchDelegate>)aDelegate {
if (self = [self init]) {
self.delegate = aDelegate;
}
return self;
}
- (NSString*) description {
long seconds = (long) floor([self value]);
long hours = seconds / 3600;
long minutes = (seconds / 60) % 60;
seconds = seconds % 60;
if (hours > 0) {
return [NSString stringWithFormat:@"%02ld:%02ld:%02ld", hours, minutes, seconds];
} else {
return [NSString stringWithFormat:@"%02ld:%02ld", minutes, seconds];
}
}
- (NSTimeInterval) value {
if (!self.timer) {
return self.accum;
}
return [[NSDate date] timeIntervalSinceDate:reference] + self.accum;
}
- (BOOL) isActive {
return self.timer != nil;
}
- (BOOL) isPaused {
return self.timer == nil && self.accum > 0;
}
- (BOOL) isStopped {
return self.timer == nil && self.accum == 0;
}
- (void) start {
if ([self isActive]) {
return;
}
self.reference = [NSDate date];
self.timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(tick) userInfo:nil repeats:YES];
if (self.delegate) {
[self.delegate didStart:self];
[self.delegate didChange:self];
}
}
- (void) pause {
if ([self isPaused]) {
return;
}
self.accum = [self value];
[self.timer invalidate];
self.timer = nil;
if (self.delegate) {
[self.delegate didPause:self];
}
}
- (void) reset:(NSTimeInterval) value {
self.accum = value;
self.reference = [NSDate date];
if (self.delegate) {
[self.delegate didChange:self];
}
}
- (void) stop {
if ([self isStopped]) {
return;
}
NSTimeInterval value = [self value];
self.accum = 0;
[self.timer invalidate];
self.timer = nil;
if (self.delegate) {
[self.delegate didStop:self withValue:value];
}
}
#pragma mark Private
- (void) tick {
if (self.delegate) {
[self.delegate didChange:self];
}
}
@end