iOS development Language Swift entry---automatic reference counting

Source: Internet
Author: User

iOS development language Swift Getting started serial-automatic reference counting

Swift uses the automatic reference counting (ARC) mechanism to track and manage the memory of your application. In general, Swift's memory management mechanism always plays a role, and you don't have to consider memory management yourself. ARC automatically frees its occupied memory when an instance of the class is no longer in use.
However, in a few cases, ARC needs more information about the relationship between your code in order to help you manage memory. This chapter describes these situations and shows you how to enable ARC to manage the memory of your application.
Attention
The reference count is applied only to instances of the class. struct and enum types are value types, not reference types, and are not stored and passed by reference.
Working mechanism of automatic reference counting
Each time you create a new instance of a class, ARC allocates a chunk of memory to store the information for the instance. The memory contains the type information of the instance and the values of all related properties of the instance. In addition, when an instance is no longer in use, ARC releases the memory occupied by the instance and allows the freed memory to be used for other purposes. This ensures that instances that are no longer being used will not occupy memory space all the time.
However, when ARC reclaims and frees an instance that is being used, the instance's properties and methods are no longer accessible and callable. In fact, if you try to access this instance, your application is likely to crash.
To ensure that instances in use are not destroyed, ARC tracks and calculates how many properties, constants, and variables each instance is referencing. ARC will not destroy this instance if the instance has a reference number of one.
To make it possible, whether you assign an instance to a property, a constant or a variable, a property, a constant, or a variable, a strong reference is created on this instance. This is called a strong reference because it keeps the instance firmly in place, as long as the strong reference is still there and the instance is not allowed to be destroyed.
  

Automatic Reference Counting Practice

The following example shows how automatic reference counting works. The example begins with a simple person class and defines a constant attribute called name:

class Person {    name: String    init(name: String) {        self.namename        println("\(name) is being initialized")    }    deinit {        println("\(name) is being deinitialized")    }}

The person class has a constructor that assigns a value to the instance's Name property and prints out information to indicate that the initialization process takes effect.  The person class also has a destructor, which also prints the information as the instance is destroyed. The next code snippet defines three types as person? Variables that are used to establish multiple references to the new person instance in the order in which they are in the code fragment. Since these variables are defined as optional types (person, not person), their values are automatically initialized to nil and are not currently referenced to instances of the person class.

var reference1: Person?var reference2: Person?var reference3: Person?

Now you can create a new instance of the person class and assign it to one of three variables:

"John Appleseed")// prints "John Appleseed is being initialized”

It should be noted that "John Appleseed is being initialized" will be printed when you invoke the constructor of the person class.  This allows you to determine that the constructor is executed. Because a new instance of the person class is assigned to the REFERENCE1 variable, a strong reference is established between Reference1 to a new instance of the person class.  Because of this strong reference, ARC ensures that the person instance is kept in memory and not destroyed. If you assign the same person instance to the other two variables, the instance will have two more strong references:

reference2 = reference1reference3 = reference1

Now there are three strong references to this person instance. If you break two strong references by assigning nil to two variables () including the first strong reference), only a strong reference is left, and the person instance is not destroyed:

reference2 = reference1reference3 = reference1

Arc destroys the person instance when the third, or last, strong reference is broken, which means that you no longer use the person instance:

nil"John Appleseed is being deinitialized"
A cyclic strong reference between class instances

In the example above, ARC tracks the number of references to your newly created person instance and destroys it when the person instance is no longer needed. However, we may write such code that a class never has 0 strong references. This happens when two class instances keep each other's strong references and keep the other party from being destroyed.  This is called a cyclic strong reference. You can override a strong reference by defining a relationship between classes as a weak reference or without a primary reference, which resolves the issue of circular strong references. Specific procedures are described in resolving cyclic strong references between class instances.  However, before you learn how to solve a cyclic strong reference, it is important to understand how it is produced. The following shows an example of a loop-strong reference that is inadvertently generated. The example defines two classes: person and apartment, used to model the apartment and its inhabitants

class Person {    letString    String) { self.name = name }    var apartment: Apartment?    deinit { println("\(name) is being deinitialized") }}
class Apartment {    number: Int    init(number: Int) { self.numbernumber }    var tenant: Person?    deinit { println("Apartment #\(number) is being deinitialized") }}

Each instance of the person has a property of type string, named Name, and an optional apartment attribute that is initialized to nil.  The Apartment property is optional because a person does not always own an apartment. Similarly, each apartment instance has a property called number, which is of type int, and has an optional tenant attribute initialized to nil.  The Tenant property is optional because an apartment does not always have residents. The two classes all define destructors to output information when a class instance is refactored.  This allows you to know if the instances of person and apartment have been destroyed as expected. The following code snippet defines two variables for the optional type John and Number73, and is set to the following apartment and person instances respectively. Both of these variables are initialized to nil and are optional:

var john: Person?var number73: Apartment?

Now you can create specific person and apartment instances and assign class instances to the John and number73 variables:

john = Person(name: "John Appleseed")number73 = Apartment(number: 73)

After two instances are created and assigned, a strongly referenced relationship is represented. Variable John now has a strong reference to the person instance, and the variable number73 has a strong reference to the apartment instance:
Now you can associate these two instances so that people can have an apartment and the apartment has tenants. Note that an exclamation mark is used to expand and access an instance of an optional variable in John and number73 so that the properties of an instance can be assigned:

john = Person(name: "John Appleseed")number73 = Apartment(number: 73)

After you associate two instances with a strongly-referenced relationship:
Unfortunately, after you associate the two instances together, a cyclic strong reference is created. The person instance now has a strong reference to the apartment instance, and the apartment instance has a strong reference to the person instance. Therefore, when you break a strong reference that is held by the John and number73 variables, the reference count does not drop to 0 and the instance is not destroyed by the ARC:

nilnil

Note that when you set these two variables to nil, no destructor is called.  A strong reference loop prevents the destruction of the person and apartment class instances and causes a memory leak in your application. After you assign John and number73 to nil, strong reference relationships such as:
A strong reference relationship between the person and the apartment instance is preserved and will not be disconnected.  Resolving cyclic strong references between instances Swift provides two ways to resolve the cyclic strong reference problem that you encounter when you use the properties of a class: weak references (weak reference) and non-primary references (unowned reference). Weak and no-primary references allow one instance in a circular reference to refer to another instance without maintaining a strong reference.  Such instances can reference each other without generating a cyclic strong reference. Use weak references for instances that will become nil in the life cycle.  Instead, an instance of nil is never assigned to an initialization assignment, using a no-primary reference. Weak reference weak references do not hold the referenced instance firmly and do not prevent the ARC from destroying the referenced instance. This behavior prevents the reference from becoming a cyclic strong reference.  When declaring a property or variable, precede the weak keyword to indicate that it is a weak reference. In the life cycle of an instance, a weak reference can prevent a circular strong reference if the reference does not have a value at some point. If the reference always has a value, you can use a no-primary reference, which is described in a no-master reference.  In the apartment example above, there are sometimes no "residents" in an apartment's life cycle, so it is appropriate to use weak references to resolve cyclic strong references. Note A weak reference must be declared as a variable, indicating that its value can be modified at run time.  A weak reference cannot be declared as a constant. Because a weak reference can have no value, you must declare each weak reference to be an optional type.  Optional types are recommended in the Swift language to represent types that may not have a value. Because a weak reference does not persist the referenced instance, even if the reference exists, the instance may be destroyed. Therefore, ARC automatically assigns a value of nil to the referenced instance after it is destroyed.  You can check the existence of a weak reference like any other optional value, and you will never encounter an instance that has been destroyed without being present. The following example is consistent with the example above for the person and apartment, but there is an important difference. This time, the tenant property of apartment is declared as a weak reference:

iOS development Language Swift entry---automatic reference counting

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.