Skip to content

Instantly share code, notes, and snippets.

@marcorei
Created September 1, 2016 10:02
Show Gist options
  • Save marcorei/85a10a1b107f5aed29caf562b14f3d6f to your computer and use it in GitHub Desktop.
Save marcorei/85a10a1b107f5aed29caf562b14f3d6f to your computer and use it in GitHub Desktop.
Test if closures alone create reference cycles
import Foundation
class Alf {
static var numberOfInstances = 0
init() {
Alf.numberOfInstances += 1
print("Alf instances: \(Alf.numberOfInstances)")
}
deinit {
Alf.numberOfInstances -= 1
print("Alf instance: \(Alf.numberOfInstances)")
}
}
class Bernd {
static var numberOfInstances = 0
let grillen:String
init(grillen:String = "gepflegt") {
self.grillen = grillen
Bernd.numberOfInstances += 1
print("Bernd instances: \(Bernd.numberOfInstances)")
}
deinit {
Bernd.numberOfInstances -= 1
print("Bernd instance: \(Bernd.numberOfInstances)")
}
}
var closure: (() -> (() -> ()))?
closure = {
_ in
var bernd = Bernd()
var innerClosure : () -> () = {
_ in
print(bernd.grillen)
var alf = Alf()
}
bernd = Bernd(grillen: "ungepflegt")
return innerClosure
}
var secondClosure: (()->())? = closure!()
secondClosure!()
secondClosure!()
secondClosure = nil
@marcorei
Copy link
Author

marcorei commented Sep 1, 2016

prints:

Bernd instances: 1
Bernd instances: 2
Bernd instance: 1
ungepflegt
Alf instances: 1
Alf instance: 0
ungepflegt
Alf instances: 1
Alf instance: 0
Bernd instance: 0

So everything should get collected by GC deallocated, ARC seems not to be problematic in this case!

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