Created
July 22, 2015 22:03
-
-
Save hiroshi-maybe/5b7cc2163ec2118afb48 to your computer and use it in GitHub Desktop.
Swift research about capture in closure
This file contains hidden or 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
| var x: X? = X() | |
| // leaks if closure1 is called, and it does not capture self by [unowned self] | |
| //x!.closure1() | |
| // if capture self, crashes because x is deallocated befor closure is called. | |
| x!.method() | |
| x = nil | |
| extension NSTimer { | |
| class NSTimerCallbackHolder : NSObject { | |
| var callback: () -> () | |
| init(callback: () -> ()) { | |
| self.callback = callback | |
| } | |
| func tick(timer: NSTimer) { | |
| callback() | |
| } | |
| } | |
| class func scheduledTimerWithTimeInterval(ti: NSTimeInterval, repeats yesOrNo: Bool, closure: () -> ()) -> NSTimer! { | |
| var holder = NSTimerCallbackHolder(callback: closure) | |
| holder.callback = closure | |
| return NSTimer.scheduledTimerWithTimeInterval(ti, target: holder, selector: Selector("tick:"), userInfo: nil, repeats: yesOrNo) | |
| } | |
| } | |
| extension NSTimer { | |
| class func setTimeout(ti: NSTimeInterval, closure: ()->()) { | |
| NSTimer.scheduledTimerWithTimeInterval(ti, repeats: false, closure: closure) | |
| } | |
| } | |
| class X { | |
| var x = 0 | |
| deinit { | |
| println("X deallocated") | |
| } | |
| func method() { | |
| NSTimer.setTimeout(3.0, closure: { | |
| // crashed if captured by `[unowned self] in` | |
| println(self.x+1) | |
| }) | |
| } | |
| lazy var closure1: ()->() = { [unowned self] in | |
| // leaks without `[unowned self] in` | |
| println(self.x) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment