Reference cycle example
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 | |
import PlaygroundSupport | |
PlaygroundPage.current.needsIndefiniteExecution = true | |
class Child { | |
func bar(completion: @escaping () -> Void) { | |
DispatchQueue.main.async { | |
completion() | |
} | |
} | |
} | |
class Parent { | |
var child = Child() | |
var x = 0 | |
func foo() { | |
self.child.bar { | |
/** | |
By using `self`, we are capturing the parent instance, | |
and passing it to the Child trhough the closure. | |
But the parent already contains a reference to child, neither child | |
will be able to release parent, nor parent will release child. | |
*/ | |
self.x = 42 | |
print(self.x) // 42 | |
} | |
print(self.x) // 0 | |
} | |
} | |
let parent = Parent() | |
parent.foo() |
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 | |
import PlaygroundSupport | |
PlaygroundPage.current.needsIndefiniteExecution = true | |
class Child { | |
func bar(completion: @escaping () -> Void) { | |
DispatchQueue.main.async { | |
completion() | |
} | |
} | |
} | |
class Parent { | |
var child = Child() | |
var x = 0 | |
func foo() { | |
self.child.bar { | |
unowned let unownedSelf = self | |
unownedSelf.x = 42 | |
print(unownedSelf.x) // 0 | |
} | |
print(self.x) // 0 | |
} | |
} | |
let parent = Parent() | |
parent.foo() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment