Skip to content

Instantly share code, notes, and snippets.

@nunogoncalves
Last active August 29, 2015 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nunogoncalves/b399eac12e9b033a9fee to your computer and use it in GitHub Desktop.
Save nunogoncalves/b399eac12e9b033a9fee to your computer and use it in GitHub Desktop.
Gist to avoid Strong Reference Cycles when using closures
//: 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