Created
February 28, 2015 17:40
-
-
Save hisui/f03739aae837519b4aaa to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
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.. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In this code, the use-side object (=
Test
) of the control is passed as argument ofMyControl #addClosureFor
, and its reference is weakly-referenced in the weak capture list. Consequently, no cyclic-reference is formed as withUIControl#addTarget
.