Weak references

When declaring an attribute or variable, prefix it with the weak keyword to indicate that it is a weak reference. Weak references are defined as optional type variables, not constants, because defined types can be assigned to nil.

case

class Person {
    let name: String
    init(name: String) { self.name = name }
    var apartment: Apartment?
    deinit { print("\(name) is being deinitialized") }
}

class Apartment {
    let unit: String
    init(unit: String) { self.unit = unit }
    weak var tenant: Person?
    deinit { print("Apartment \(unit) is being deinitialized")}}Copy the code

Create a strong reference between two variables (John and unit4A) and associate two instances:

var john: Person?
var unit4A: Apartment?

john = Person(name: "John Appleseed")
unit4A = Apartment(unit: "4A") john! .apartment = unit4A unit4A! .tenant = johnCopy the code

The reference relationship between the two linked instances is shown below:

The Person instance still holds a strong reference to the Apartment instance, but the Apartment instance only holds a weak reference to the Person instance. This means that when you break the strong reference held by the John variable, there are no more strong references to the Person instance:

Since there is no longer a strong reference to the Person instance, it will be destroyed:

// Print "John Appleseed is being deinitialized"Copy the code

The only remaining strong reference to an instance of Apartment comes from the variable unit4A. If you disconnect the strong reference, there are no more strong references to the Apartment instance:

Apartment

// Print "Apartment 4A is being deinitialized"Copy the code

The above two pieces of code show that after the variables John and unit4A are assigned nil, the destructors for both the Person and Apartment instances print “destroy”. This proves that the citation cycle is broken.

Note that in systems that use garbage collection, weak Pointers are sometimes used to implement simple buffering mechanisms, since objects without strong references are destroyed only when memory pressure triggers garbage collection. But in ARC, once the last strong reference to a value is removed, it is destroyed immediately, making weak references unsuitable for the above purposes.

Source: http://www.piggybear.net/?p=675