Depth: Memory leakage caused by arc

Source: Internet
Author: User

IOS provides the arc function, which greatly simplifies the code for memory management.

However, using arc does not mean that there will be no memory leakage. If used improperly, the memory leakage will still occur.

The following lists two memory leaks.

1. cycle reference

A has an attribute that references B and B has an attribute that references a. If both are strong references, both objects cannot be released.

This problem often occurs when delegate is declared as the strong attribute.

For example,

@ Interface sampleviewcontroller

@ Property (nonatomic, strong) sampleclass * sampleclass;

@ End

@ Interface sampleclass

@ Property (nonatomic, strong) sampleviewcontroller * delegate;

@ End

 

In the above example, the solution is to change the strong of the delegate attribute of sampleclass to assing.

 

2. endless loop

If an infinite loop exists in a viewcontroller, The viewcontroller cannot be released even if the view corresponding to the viewcontroller is disabled.

This problem often occurs in animation processing.

For example,

For example,

Catransition * transition = [catransition animation];

Transition. Duration = 0.5;

Tansition. repeatcount = huge_vall;

[Self. View. layer addanimation: Transition forkey: "myanimation"];

 

In the preceding example, the number of times the animation repeats is set to huge_vall. A large value is basically equivalent to an infinite loop.

The solution is to stop the animation when the viewcontroller is disabled.

-(Void) viewwilldisappear :( bool) animated {

[Self. View. layer removeallanimations];

}

 

Of course, there are more than two types of memory leaks.

That is, when using arc, we also need to have a deep understanding of the memory management mechanism of IOS so as to effectively avoid Memory leakage.

Depth: Memory leakage caused by arc

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.