Skip to content

Instantly share code, notes, and snippets.

@robertmryan
Last active October 25, 2019 17:32
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robertmryan/03fa869f35cfc2d6a780 to your computer and use it in GitHub Desktop.
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 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")
}
}
@kaleemasadmughal
Copy link

Good Example

@m41w4r3exe
Copy link

really good example to explain it clearly and simply, thanks

@joehinkle11
Copy link

Very helpful. Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment