First we create a circular reference
var Nameb: ((), ())?Overridefunc viewdidload () {super.viewdidload () let Bu=UIButton (type:. Contactadd) Bu.addtarget (Self, Action:"Tap", forControlEvents:. touchupinside) View.addsubview (BU) run {print ("name") Self.view.backgroundColor=Uicolor.greencolor ()}} Func tap () {print ("Tap") dismissviewcontrolleranimated (true) {(), VoidinchPrint ("dismissviewcontrolleranimated"}}}} Func run (name: ()-()) {print ("Execute Code") Nameb=name Name ()} deinit {print ("Deinit") }
In the code we create a global variable nameb, then we pass in a closure when calling the method run, in the closure we use Self.view ... In this case, the packet closure is quoted as self,
And then we assign a value to the NAMEB in run, which is why the Controller self also refers to the closure, so it causes a circular reference
Can execute the above code certainly won't go Deint method
It is not difficult to solve the circular reference of a closure, we solve circular references in OC use weak to decorate a self, as in Swift
weak var weakself = self
But be aware that the weakself here is packaged into a <optional> type, so it is mandatory to parse when used
classViewcontroller2:uiviewcontroller {var nameb: ()())?Overridefunc viewdidload () {super.viewdidload () let Bu=UIButton (type:. Contactadd) Bu.addtarget (Self, Action:"Tap", forControlEvents:. touchupinside) View.addsubview (BU) weak var weakself=Self Run {print ("name") weakself!. View.backgroundcolor =Uicolor.greencolor ()}} Func tap () {print ("Tap") dismissviewcontrolleranimated (true) {(), VoidinchPrint ("dismissviewcontrolleranimated"}}}} Func run (name: ()-()) {print ("Execute Code") Nameb=name Name ()} deinit {print ("Deinit") }}
That would definitely go into the Deinit method.
Circular reference of closures in Swift