|
24 | 24 |
|
25 | 25 | import Foundation |
26 | 26 |
|
27 | | -private class NSTimerActor { |
28 | | - let block: () -> Void |
29 | | - |
30 | | - init(_ block: () -> Void) { |
31 | | - self.block = block |
32 | | - } |
33 | | - |
34 | | - @objc func fire() { |
35 | | - block() |
36 | | - } |
37 | | -} |
38 | | - |
39 | 27 | extension NSTimer { |
40 | 28 | /// Create a timer that will call `block` once after the specified time. |
41 | 29 | /// |
42 | 30 | /// - Note: The timer won't fire until it's scheduled on the run loop. |
43 | 31 | /// Use `NSTimer.after` to create and schedule a timer in one step. |
44 | 32 | /// - Note: The `new` class function is a workaround for a crashing bug when using convenience initializers (rdar://18720947) |
45 | | - |
| 33 | + |
46 | 34 | public class func new(after interval: NSTimeInterval, _ block: () -> Void) -> NSTimer { |
47 | | - let actor = NSTimerActor(block) |
48 | | - return self.init(timeInterval: interval, target: actor, selector: "fire", userInfo: nil, repeats: false) |
| 35 | + return CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent() + interval, 0, 0, 0) { _ in |
| 36 | + block() |
| 37 | + } |
49 | 38 | } |
50 | | - |
51 | 39 | /// Create a timer that will call `block` repeatedly in specified time intervals. |
52 | 40 | /// |
53 | 41 | /// - Note: The timer won't fire until it's scheduled on the run loop. |
54 | 42 | /// Use `NSTimer.after` to create and schedule a timer in one step. |
55 | 43 | /// - Note: The `new` class function is a workaround for a crashing bug when using convenience initializers (rdar://18720947) |
56 | | - |
| 44 | + |
57 | 45 | public class func new(every interval: NSTimeInterval, _ block: () -> Void) -> NSTimer { |
58 | | - let actor = NSTimerActor(block) |
59 | | - return self.init(timeInterval: interval, target: actor, selector: "fire", userInfo: nil, repeats: true) |
| 46 | + return CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent() + interval, interval, 0, 0) { _ in |
| 47 | + block() |
| 48 | + } |
60 | 49 | } |
61 | | - |
| 50 | + |
| 51 | + |
62 | 52 | /// Create and schedule a timer that will call `block` once after the specified time. |
63 | 53 |
|
64 | 54 | public class func after(interval: NSTimeInterval, _ block: () -> Void) -> NSTimer { |
|
0 commit comments