Created
September 28, 2015 03:34
-
-
Save onevcat/2d1ceff1c657591eebde to your computer and use it in GitHub Desktop.
NSTimer extension which breaks the retain cycle in Swift.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private class Block<T> { | |
let f : T | |
init (_ f: T) { self.f = f } | |
} | |
extension NSTimer { | |
static func xxx_scheduledTimerWithTimeInterval(ti: NSTimeInterval, block: ()->(), repeats: Bool) -> NSTimer { | |
return self.scheduledTimerWithTimeInterval(ti, target: | |
self, selector: "xxx_blcokInvoke:", userInfo: Block(block), repeats: repeats) | |
} | |
static func xxx_blcokInvoke(timer: NSTimer) { | |
if let block = timer.userInfo as? Block<()->()> { | |
block.f() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@vin-zhou you can call invalidate in viewDidDisappear? Because run loop will maintain strong reference to timer, timer to ViewController. So call invalidate it first to release timer then ViewController.