blob: 2774c08362bd680819826e9b17d0b26449222c1f (
plain)
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
|
//
// SDLTimer.m
//
#import "SDLTimer.h"
NS_ASSUME_NONNULL_BEGIN
@protocol SDLTimerTargetDelegate <NSObject>
- (void)timerElapsed;
@end
@interface SDLTimerTarget : NSObject
@property (nonatomic, weak) id<SDLTimerTargetDelegate> delegate;
@end
@implementation SDLTimerTarget
- (instancetype)initWithDelegate:(id)delegate {
self = [super init];
if (self) {
_delegate = delegate;
}
return self;
}
- (void)timerElapsed {
if ([self.delegate conformsToProtocol:@protocol(SDLTimerTargetDelegate)]) {
[_delegate timerElapsed];
}
}
@end
@interface SDLTimer () <SDLTimerTargetDelegate>
@property (strong, nonatomic, nullable) NSTimer *timer;
@property (assign, nonatomic) BOOL timerRunning;
@property (assign, nonatomic) BOOL repeat;
@end
@implementation SDLTimer
- (instancetype)init {
if (self = [super init]) {
_duration = 0;
_timerRunning = NO;
}
return self;
}
- (instancetype)initWithDuration:(float)duration {
return [self initWithDuration:duration repeat:NO];
}
- (instancetype)initWithDuration:(float)duration repeat:(BOOL)repeat {
self = [super init];
if (self) {
_duration = duration;
_repeat = repeat;
_timerRunning = NO;
}
return self;
}
- (void)dealloc {
[self cancel];
}
- (void)start {
if (self.duration > 0) {
[self stopAndDestroyTimer];
SDLTimerTarget *timerTarget = [[SDLTimerTarget alloc] initWithDelegate:self];
self.timer = [NSTimer timerWithTimeInterval:_duration target:timerTarget selector:@selector(timerElapsed) userInfo:nil repeats:_repeat];
[[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
self.timerRunning = YES;
}
}
- (void)cancel {
[self stopAndDestroyTimer];
if (self.timerRunning && self.canceledBlock != nil) {
self.timerRunning = NO;
self.canceledBlock();
}
self.timerRunning = NO;
}
- (void)timerElapsed {
if (self.repeat == NO) {
[self stopAndDestroyTimer];
self.timerRunning = NO;
}
if (self.elapsedBlock != nil) {
self.elapsedBlock();
}
}
- (void)stopAndDestroyTimer {
if (self.timer != nil) {
[self.timer invalidate];
self.timer = nil;
}
}
@end
NS_ASSUME_NONNULL_END
|