From ad051f54c57586a8cc64e6984cdc36fa773101c4 Mon Sep 17 00:00:00 2001 From: Hoan Pham Date: Wed, 24 Jun 2015 10:13:23 +0700 Subject: [PATCH] add timer into closure --- Src/SwiftyTimer.swift | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/Src/SwiftyTimer.swift b/Src/SwiftyTimer.swift index 3b49dcf..f468cff 100644 --- a/Src/SwiftyTimer.swift +++ b/Src/SwiftyTimer.swift @@ -24,15 +24,18 @@ import Foundation +import Foundation + private class NSTimerActor { - var block: () -> Void + var block: (NSTimer!) -> Void + var timer: NSTimer! - init(_ block: () -> Void) { + init(_ block: (NSTimer!) -> Void) { self.block = block } @objc func fire() { - block() + block(timer) } } @@ -44,9 +47,12 @@ extension NSTimer { /// **Note:** the timer won't fire until it's scheduled on the run loop. /// Use `NSTimer.after` to create and schedule a timer in one step. - public class func new(after interval: NSTimeInterval, _ block: () -> Void) -> NSTimer { + public class func new(after interval: NSTimeInterval, _ block: (NSTimer!) -> Void) -> NSTimer { + let timer: NSTimer! let actor = NSTimerActor(block) - return self.init(timeInterval: interval, target: actor, selector: "fire", userInfo: nil, repeats: false) + timer = self.init(timeInterval: interval, target: actor, selector: "fire", userInfo: nil, repeats: false) + actor.timer = timer + return timer } /// Create a timer that will call `block` repeatedly in specified time intervals. @@ -54,14 +60,17 @@ extension NSTimer { /// **Note:** the timer won't fire until it's scheduled on the run loop. /// Use `NSTimer.every` to create and schedule a timer in one step. - public class func new(every interval: NSTimeInterval, _ block: () -> Void) -> NSTimer { + public class func new(every interval: NSTimeInterval, _ block: (NSTimer!) -> Void) -> NSTimer { + let timer: NSTimer! let actor = NSTimerActor(block) - return self.init(timeInterval: interval, target: actor, selector: "fire", userInfo: nil, repeats: true) + timer = self.init(timeInterval: interval, target: actor, selector: "fire", userInfo: nil, repeats: true) + actor.timer = timer + return timer } /// Create and schedule a timer that will call `block` once after the specified time. - public class func after(interval: NSTimeInterval, _ block: () -> Void) -> NSTimer { + public class func after(interval: NSTimeInterval, _ block: (NSTimer!) -> Void) -> NSTimer { let timer = NSTimer.new(after: interval, block) timer.start() return timer @@ -69,7 +78,7 @@ extension NSTimer { /// Create and schedule a timer that will call `block` repeatedly in specified time intervals. - public class func every(interval: NSTimeInterval, _ block: () -> Void) -> NSTimer { + public class func every(interval: NSTimeInterval, _ block: (NSTimer!) -> Void) -> NSTimer { let timer = NSTimer.new(every: interval, block) timer.start() return timer