Last active
August 29, 2015 14:26
-
-
Save nunogoncalves/b399eac12e9b033a9fee to your computer and use it in GitHub Desktop.
Gist to avoid Strong Reference Cycles when using closures
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
//: Playground - noun: a place where people can play | |
import UIKit | |
class LoginView { | |
var loginSuccessCallback: ((Int)->Void)? | |
init() { | |
println("login: - hello") | |
} | |
func login() { | |
println("loging in") | |
loginSuccessCallback?(2) | |
} | |
deinit { | |
println("login: - goodbye") | |
} | |
} | |
class Controller { | |
var login: LoginView? | |
init() { | |
login = LoginView() | |
//Toggle the following lines' comments and you will notice the "login: - goodbye" won't be print | |
// login?.loginSuccessCallback = loginCallback | |
login?.loginSuccessCallback = { [unowned self] anInt in | |
self.loginCallback(anInt) | |
} | |
} | |
func requestLogin() { | |
login!.login() | |
} | |
func loginCallback(anInt: Int) { | |
println("yay logged in") | |
} | |
} | |
var c: Controller? = Controller() | |
c!.requestLogin() | |
c = nil |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment