ios - How to set a weak reference to a closure/function in Swift? -
in hmsegmentedcontrol
, i'd set segmentedcontrol.indexchangeblock
instance method handle action. official example is: https://github.com/heshammegid/hmsegmentedcontrol/blob/master/hmsegmentedcontrolexample/hmsegmentedcontrolexample/viewcontroller.m (line 63 ~ 68), that's objective-c.
in swift, functions first class citizens. wanna set instance method block property.
code lead circular reference, seems should define weak reference:
class examplevc: uiviewcontroller { var segmentedcontrolindex: int = 0 override func viewdidload() { let segmentedcontrol3 = hmsegmentedcontrol(sectionimages: ... , sectionselectedimages: ... ) segmentedcontrol3.frame = ... segmentedcontrol3.indexchangeblock = someinstancemethod } func someinstancemethod(index: int) { segmentedcontrolindex = index } }
however, cannot define weak reference non-class type. can do? legal this?
instead of defining weak reference closure, should use "capture list" in closure.
segmentedcontrol3.indexchangeblock = { [unowned self] in self.someinstancemethod($0) }
as far know, way avoid strong reference cycles.
Comments
Post a Comment