Created
March 18, 2018 17:59
-
-
Save chefnobody/3ca6f7795d004512a4db8e009f77244a to your computer and use it in GitHub Desktop.
Quick demo of creating and breaking a retain cycle
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 Foundation | |
protocol SendDataDelegate: class {} | |
// Only need to use "weak" if the delegate is of type `class`? structs and enums are value types, not reference types so they don't create retain cycles. | |
class SendingVC { | |
weak var delegate: SendDataDelegate? // Remove "weak" and you create a strong reference between both these *VC objects | |
} | |
class ReceivingVC: SendDataDelegate { | |
lazy var sendingVC: SendingVC = { | |
let vc = SendingVC() | |
vc.delegate = self | |
return vc | |
}() | |
deinit { | |
print("I'm gone baby!") | |
} | |
} | |
//var receivingVC:ReceivingVC? = ReceivingVC() | |
// Will create a retain cycle w/o the above "weak" | |
//var sendingVC = receivingVC?.sendingVC // commenting this line won't create the strong reference from sendingVC back to ReceivingVC. Can be fixed by making the delegate property weak | |
//receivingVC = nil | |
class Foo { | |
var completed:(()->())? | |
var name = "Foo" | |
init() { | |
// creates a retain cycle | |
self.completed = { print("\(self.name) completed") } | |
// weakly references self thus avoiding the retain cycle | |
self.completed = { [weak self] in | |
print("\(self?.name) completed") | |
} | |
} | |
deinit { | |
print("bye bye!") | |
} | |
} | |
//var foo: Foo? = Foo() | |
//foo = nil | |
class Bar { | |
var done:(()->())? | |
var name = "Bar" | |
init() { | |
self.done = { print("\(self.name) is Donezo!") } | |
// Not sure why we'd care about the retain cycle | |
// if we *know* the instance of Bar will never be deleted? | |
self.done = { [unowned self] in | |
print("\(self.name) is Donezo!") | |
} | |
} | |
deinit { | |
print("What's done is done!") | |
} | |
} | |
// If bar will never be nil (because its not Optional) | |
// You'll still have a retain cycle in that closure assignment above. | |
var bar:Bar = Bar() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment