-
-
Save robertmryan/03fa869f35cfc2d6a780 to your computer and use it in GitHub Desktop.
strong delegate causing strong reference cycle (even with `struct`); making it `weak` solves this
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
// this is strong reference cycle | |
protocol MyStructDelegate { | |
func didSomethingHappen() | |
} | |
struct MyStruct { | |
var delegate: MyStructDelegate | |
init(delegate: MyStructDelegate) { | |
self.delegate = delegate | |
} | |
} | |
class SecondViewController: UIViewController, MyStructDelegate { | |
var myStruct: MyStruct! | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
myStruct = MyStruct(delegate: self) | |
} | |
func didSomethingHappen() { | |
println(__FUNCTION__) | |
} | |
deinit { | |
println("Never get here") | |
} | |
} | |
// this is not strong reference cycle | |
protocol MyStructDelegate : class { | |
func didSomethingHappen() | |
} | |
struct MyStruct { | |
unowned var delegate: MyStructDelegate | |
init(delegate: MyStructDelegate) { | |
self.delegate = delegate | |
} | |
} | |
class SecondViewController: UIViewController, MyStructDelegate { | |
var myStruct: MyStruct! | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
myStruct = MyStruct(delegate: self) | |
} | |
func didSomethingHappen() { | |
println(__FUNCTION__) | |
} | |
deinit { | |
println("Got here") | |
} | |
} |
really good example to explain it clearly and simply, thanks
Very helpful. Thank you
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Good Example