Swift Introductory Tutorials 17-arc and strength references

Source: Internet
Author: User

ARC
Full name automatic reference counting, is a memory management mechanism. When the number of strong references to a block of memory equals 0, the memory is freed.
Because enumerations and structs are value types in swift, they are not stored and passed by reference, so only instances of the class in Swift are automatically reference counted.
rule: At the beginning of the creation, the reference count of the instance of the class is 1, no strong reference is added, the reference count is incremented by 1, and the reference count is minus 1 after each strong reference is nil. Weak references do not increase the reference count, keyword weak
Note that you cannot access memory that has already been freed, which can cause the program to crash.
I. Strong and weak references
Use the representation to be intuitive

A strong reference, a weak reference.



Second, the case analysis
The destructor is called before the object memory is freed, and the corresponding cleanup work is done, such as opening the file to close the file in the destructor, such as adding observer to remove in the destructor.

The key word of the destructor is Deinit

To break a strong reference by assigning nil to the object

Class Csdn{var name:string;   Init (csdnname:string) {self.name = Csdnname}deinit{println ("Memory will be freed")}}var Instance1 = CSDN (csdnname: "Hello HWC")   //reference count is 1var Instance2 = instance1//reference count is 2weak var instance3 = instance2//reference count is 2instance1 = nil//reference count = 1instance2 = Ni L//reference count is 0, memory is freed, output "memory is going to be freed"//println (instance3.name) So the call is wrong, because the memory has been freed

Swift Introductory Tutorials 17-arc and strength references

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.