Skip to content

Instantly share code, notes, and snippets.

@volonbolon
Created December 20, 2017 23:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save volonbolon/7a575b4d5c5a45d22601ca1ec9df8a68 to your computer and use it in GitHub Desktop.
Save volonbolon/7a575b4d5c5a45d22601ca1ec9df8a68 to your computer and use it in GitHub Desktop.
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