iOS avoids circular references

Source: Internet
Author: User

A similar network request can cause a circular reference, but

If the network Request object is a local variable, you must use self, cannot use weakself, otherwise, once the current method object is destroyed, then the weakself is empty (if this is the case, it is another matter), because the block will be copied into the heap, The memory in the current method is then destroyed from the stack, and self is nil.

If the object that the network requests is a member variable, you must use Weakself, and you cannot use self to avoid circular references.

In addition, if you nest network requests, you need to consider it as a whole, "it is wrong to use each level in accordance with the rules described above." Use weakself as much as possible in order to ensure self exists. Even if self disappears, you may not execute the associated code, but do not cause a circular reference

Why does the block in GCD need not use weakself?

The reason is that self does not have a reference to the block, and the block is automatically destroyed after execution, except that the block has a unilateral reference to it.

And under what circumstances will there be circular references? As mentioned above, self holds blocks (instance variables, attributes, and so on), and the block is used by the asihttprequest, or the object (a property, for example, the) itself has a reference to the block (a callback in ASIHTTPRequest Block's properties), and block references self.

Self----(property or variable of a non-local variable)-----> block----->self

Self-----(a property or variable of a non-local variable)-----> ASIHTTPRequest-----(a property or variable of a non-local variable)-----> block----->self

See Http://stackoverflow.com/questions/21987067/using-weak-self-in-dispatch-async-function for details.

iOS avoids circular references

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.