Add a variant of `every` and `new(every:)` that takes a closure with … · liam-i/SwiftyTimer@61335a1 · GitHub
Skip to content

Commit 61335a1

Browse files
committed
Add a variant of every and new(every:) that takes a closure with NSTimer passed in
1 parent 8cac701 commit 61335a1

3 files changed

Lines changed: 54 additions & 2 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions

‎Sources/SwiftyTimer.swift‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ extension NSTimer {
3636
block()
3737
}
3838
}
39+
3940
/// Create a timer that will call `block` repeatedly in specified time intervals.
4041
///
4142
/// - Note: The timer won't fire until it's scheduled on the run loop.
@@ -47,7 +48,21 @@ extension NSTimer {
4748
block()
4849
}
4950
}
50-
51+
52+
/// Create a timer that will call `block` repeatedly in specified time intervals.
53+
/// (This variant also passes the timer instance to the block)
54+
///
55+
/// - Note: The timer won't fire until it's scheduled on the run loop.
56+
/// Use `NSTimer.after` to create and schedule a timer in one step.
57+
/// - Note: The `new` class function is a workaround for a crashing bug when using convenience initializers (rdar://18720947)
58+
59+
@nonobjc public class func new(every interval: NSTimeInterval, _ block: NSTimer -> Void) -> NSTimer {
60+
var timer: NSTimer!
61+
timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent() + interval, interval, 0, 0) { _ in
62+
block(timer)
63+
}
64+
return timer
65+
}
5166

5267
/// Create and schedule a timer that will call `block` once after the specified time.
5368

@@ -65,6 +80,15 @@ extension NSTimer {
6580
return timer
6681
}
6782

83+
/// Create and schedule a timer that will call `block` repeatedly in specified time intervals.
84+
/// (This variant also passes the timer instance to the block)
85+
86+
@nonobjc public class func every(interval: NSTimeInterval, _ block: NSTimer -> Void) -> NSTimer {
87+
let timer = NSTimer.new(every: interval, block)
88+
timer.start()
89+
return timer
90+
}
91+
6892
/// Schedule this timer on the run loop
6993
///
7094
/// By default, the timer is scheduled on the current run loop for the default mode.

‎SwiftyTimerTests/SwiftyTimerTests/main.swift‎

Lines changed: 28 additions & 1 deletion

0 commit comments

Comments
 (0)