Problems with block circular referencing in Swift

Source: Internet
Author: User

In sub-controller A of Navtionviewcontroller, a B control is used as its property, a block of the B control is defined, and the properties of the a controller are referenced in this block, and the block captures a at this time, forming an indirect circular reference.

Navtionviewcontroller A

A->b

B->blcok

Block--A.someprops = = = Block =>a

Even if the user exits the a controller, that is, the a controller calls the Pop method, that is, Navtionviewcontroller no longer references a, but the block of B still refers to a, when an instance of a is also stored in memory and will not be freed. There's a memory leak.

Workaround, when defining a block, use [weak self] or [unowned self] in front of its arguments.

How do I choose a weak reference or a non-primary reference?

When the instances of closures and captures are always referencing each other and are always destroyed at the same time, the captures within the closures are defined as non-primary references (using [unowned Self]).

Conversely, when a capture reference is sometimes possible nil , the capture inside the closure is defined as a weak reference (using [weak self]). A weak reference is always an optional type, and when the referenced instance is destroyed, the value of the weak reference is automatically set to nil . This allows us to check if they exist within the closures.

Problems with block circular referencing 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.