Skip to content

Instantly share code, notes, and snippets.

@hisui
Created February 28, 2015 17:40
Show Gist options
  • Save hisui/f03739aae837519b4aaa to your computer and use it in GitHub Desktop.
Save hisui/f03739aae837519b4aaa to your computer and use it in GitHub Desktop.
// Playground - noun: a place where people can play
import UIKit
class MyControl {
private var closures: [(UIControlEvents, MyControl -> ())] = []
init() {}
func addClosureFor<T: AnyObject>(event: UIControlEvents, target: T, closure: (T, MyControl) -> ())
{
closures.append((event, { [weak target] (ctrl: MyControl) -> () in
if let o = object {
closure(o, ctrl)
}
return
}))
}
func executeClosuresOf(event: UIControlEvents) {
for closure in closures {
if closure.0 == event {
closure.1(self)
}
}
}
}
class Test {
var testProperty = "Default String"
let control = MyControl()
init() {
control.addClosureFor(UIControlEvents.TouchUpInside, target: self, closure: { (o, control) -> () in
o.testProperty = "This is not making any reference cycle."
})
// control.executeClosuresOf(UIControlEvents.TouchUpInside)
}
deinit { println("released..") }
}
var test: Test? = Test()
test = nil // ==> released..
@hisui
Copy link
Author

hisui commented Feb 28, 2015

In this code, the use-side object (= Test) of the control is passed as argument of MyControl #addClosureFor, and its reference is weakly-referenced in the weak capture list. Consequently, no cyclic-reference is formed as with UIControl#addTarget.

@txaiwieser
Copy link

Awsome! :D

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