IOS face Question (ii): When to use weakself in block--from Tang Qiao

Source: Internet
Author: User

Problem

We know that in order to avoid circular references when using block, it is often necessary to use weakself and strongself to write the following code:

typeof (self) weakself = self;[ Self dosomeblockjob:^{    typeof(weakself) strongself = weakself;     if (strongself) {        ...    }}];

Then ask: when in block with self, do not need to use weak self?

Answer

The weak self is not required when the block itself is not owned by the own, but is held by another object and does not produce a circular reference. The most common code is UIView animation code, and we animateWithDuration:animations do not need to use the weak self when animating with the UIView method, because the reference holding relationship is:

    • One of UIView's animated objects holds a block
    • Block holds the self

Since self does not hold a block, there is no circular reference because there is no need to use weak self.

[UIView animatewithduration:0.2 animations:^{    1;}];

When the animation is finished, the UIView will end up holding the block, and if no other object holds the block, the Block object will be released and the block will release the hold for self. The entire memory reference relationship is lifted.

Study Questions

If you think the above problem is too simple, consider the following two topics:

    • Why do I have to write a strong self in block, what if I don't write it?
    • There is no such a demand scenario, block will produce circular references, but the business needs you can not use weak self? If so, give an example and explain how to solve the circular reference problem in this case.

IOS face Question (ii): When to use weakself in block--from Tang Qiao

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.