Skip to content

Instantly share code, notes, and snippets.

@volonbolon
Created December 20, 2017 23:41
Embed
What would you like to do?
Reference cycle example
//: 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()
//: 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