@@ -31,12 +31,18 @@ extension Timer {
3131
3232 private struct AssociatedKeys {
3333 static var repeatCounterAddress = " repeat_counter_address "
34- // static var isTimerRunning = "is_timer_running_address"
34+ static var isTimerRunning = " is_timer_running_address "
3535 }
3636
37- private var isRunning : Bool {
37+ public var isRunning : Bool {
3838 get {
39- return isValid//objc_getAssociatedObject(self, &AssociatedKeys.isTimerRunning) as? Bool ?? false
39+ return isValid && objc_getAssociatedObject ( self , & AssociatedKeys. isTimerRunning) as? Bool ?? false
40+ }
41+ set {
42+ objc_setAssociatedObject ( self ,
43+ & AssociatedKeys. isTimerRunning,
44+ newValue,
45+ . OBJC_ASSOCIATION_RETAIN_NONATOMIC)
4046 }
4147 }
4248
@@ -98,6 +104,7 @@ extension Timer {
98104
99105 public class func new( after interval: TimeInterval , _ block: @escaping ( ) -> Void ) -> Timer {
100106 return CFRunLoopTimerCreateWithHandler ( kCFAllocatorDefault, CFAbsoluteTimeGetCurrent ( ) + interval, 0 , 0 , 0 ) { timer in
107+ ( timer as! Timer ) . isRunning = false
101108 block ( )
102109 }
103110 }
@@ -120,12 +127,11 @@ extension Timer {
120127 timer = CFRunLoopTimerCreateWithHandler ( kCFAllocatorDefault, CFAbsoluteTimeGetCurrent ( ) + interval, interval, 0 , 0 ) { _ in
121128
122129 if times > 0 {
123- if timer. repeatCounter == times {
130+ if timer. repeatCounter == ( times- 1 ) {
124131 timer. invalidate ( )
125- return
126- } else {
127- timer. repeatCounter += 1
128132 }
133+ timer. repeatCounter += 1
134+
129135 }
130136
131137 block ( )
@@ -146,12 +152,12 @@ extension Timer {
146152 timer = CFRunLoopTimerCreateWithHandler ( kCFAllocatorDefault, CFAbsoluteTimeGetCurrent ( ) + interval, interval, 0 , 0 ) { _ in
147153
148154 if times > 0 {
149- if timer. repeatCounter == times {
155+ if timer. repeatCounter == ( times- 1 ) {
150156 timer. invalidate ( )
151- return
152- } else {
153- timer. repeatCounter += 1
154157 }
158+
159+ timer. repeatCounter += 1
160+
155161 }
156162
157163 block ( timer, timer. repeatCounter)
@@ -175,6 +181,7 @@ extension Timer {
175181 /// Specify `runLoop` or `modes` to override these defaults.
176182
177183 public func start( runLoop: RunLoop = . current, modes: RunLoopMode ... ) {
184+ isRunning = true
178185 let modes = modes. isEmpty ? [ . defaultRunLoopMode] : modes
179186
180187 for mode in modes {
0 commit comments