Circular reference of closures in Swift

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.