Swift3.0官方文档与中文翻译对照

Automatic Reference Counting (自动

2017-01-20  本文已影响38人  金旭峰

Swift usesAutomatic Reference Counting(ARC) to track and manage your app’s memory usage. In most cases, this means that memory management “just works” in Swift, and you do not need to think about memory management yourself. ARC automatically frees up the memory used by class instances when those instances are no longer needed.

Swift 使用自动引用计数(ARC)机制来跟踪和管理你的应用程序的内存。通常情况下,Swift 内存管理机制会一直起作用,你无须自己来考虑内存的管理。ARC 会在类的实例不再被使用时,自动释放其占用的内存。

However, in a few cases ARC requires more information about the relationships between parts of your code in order to manage memory for you. This chapter describes those situations and shows how you enable ARC to manage all of your app’s memory. Using ARC in Swift is very similar to the approach described inTransitioning to ARC Release Notesfor using ARC with Objective-C.

然而在少数情况下,为了能帮助你管理内存,ARC 需要更多的,代码之间关系的信息。本章描述了这些情况,并且为你示范怎样才能使 ARC 来管理你的应用程序的所有内存。在 Swift 使用 ARC 与在 Obejctive-C 中使用 ARC 非常类似,具体请参考过渡到 ARC 的发布说明

NOTE

Reference counting only applies to instances of classes. Structures and enumerations are value types, not reference types, and are not stored and passed by reference.

引用计数仅仅应用于类的实例。结构体和枚举类型是值类型,不是引用类型,也不是通过引用的方式存储和传递。

How ARC Works (自动引用计数的工作机制)

Every time you create a new instance of a class, ARC allocates a chunk of memory to store information about that instance. This memory holds information about the type of the instance, together with the values of any stored properties associated with that instance.

当你每次创建一个类的新的实例的时候,ARC 会分配一块内存来储存该实例信息。内存中会包含实例的类型信息,以及这个实例所有相关的存储型属性的值。

Additionally, when an instance is no longer needed, ARC frees up the memory used by that instance so that the memory can be used for other purposes instead. This ensures that class instances do not take up space in memory when they are no longer needed.

此外,当实例不再被使用时,ARC 释放实例所占用的内存,并让释放的内存能挪作他用。这确保了不再被使用的实例,不会一直占用内存空间。

However, if ARC were to deallocate an instance that was still in use, it would no longer be possible to access that instance’s properties, or call that instance’s methods. Indeed, if you tried to access the instance, your app would most likely crash.

然而,当 ARC 收回和释放了正在被使用中的实例,该实例的属性和方法将不能再被访问和调用。实际上,如果你试图访问这个实例,你的应用程序很可能会崩溃。

To make sure that instances don’t disappear while they are still needed, ARC tracks how many properties, constants, and variables are currently referring to each class instance. ARC will not deallocate an instance as long as at least one active reference to that instance still exists.

为了确保使用中的实例不会被销毁,ARC 会跟踪和计算每一个实例正在被多少属性,常量和变量所引用。哪怕实例的引用数为1,ARC都不会销毁这个实例。

To make this possible, whenever you assign a class instance to a property, constant, or variable, that property, constant, or variable makes astrong referenceto the instance. The reference is called a “strong” reference because it keeps a firm hold on that instance, and does not allow it to be deallocated for as long as that strong reference remains.

为了使上述成为可能,无论你将实例赋值给属性、常量或变量,它们都会创建此实例的强引用。之所以称之为“强”引用,是因为它会将实例牢牢地保持住,只要强引用还在,实例是不允许被销毁的。

ARC in Action (自动引用计数实践)

Here’s an example of how Automatic Reference Counting works. This example starts with a simple class calledPerson, which defines a stored constant property calledname:

下面的例子展示了自动引用计数的工作机制。例子以一个简单的Person类开始,并定义了一个叫name的常量属性:

class Person{

    let name:String

    init (name:String) {

        self.name=name  

        print("\(name)is being initialized")

    }

    deinit {

        print("\(name)is being deinitialized") 

    }

}

ThePersonclass has an initializer that sets the instance’snameproperty and prints a message to indicate that initialization is underway. ThePersonclass also has a deinitializer that prints a message when an instance of the class is deallocated.

Person类有一个构造函数,此构造函数为实例的name属性赋值,并打印一条消息以表明初始化过程生效。Person类也拥有一个析构函数,这个析构函数会在实例被销毁时打印一条消息。

The next code snippet defines three variables of typePerson?, which are used to set up multiple references to a newPersoninstance in subsequent code snippets. Because these variables are of an optional type (Person?, notPerson), they are automatically initialized with a value ofnil, and do not currently reference aPersoninstance.

接下来的代码片段定义了三个类型为Person?的变量,用来按照代码片段中的顺序,为新的Person实例建立多个引用。由于这些变量是被定义为可选类型(Person?,而不是Person),它们的值会被自动初始化为nil,目前还不会引用到Person类的实例。

var reference1:Person?

var reference2:Person?

var reference3:Person?

You can now create a new Person instance and assign it to one of these three variables:

现在你可以创建Person类的新实例,并且将它赋值给三个变量中的一个:

reference1 = Person(name:"John Appleseed")

// Prints "John Appleseed is being initialized"

Note that the message"John Appleseed is being initialized"is printed at the point that you call thePersonclass’s initializer. This confirms that initialization has taken place.

应当注意到当你调用Person类的构造函数的时候,“John Appleseed is being initialized”会被打印出来。由此可以确定构造函数被执行。

Because the newPersoninstance has been assigned to thereference1variable, there is now a strong reference fromreference1to the newPersoninstance. Because there is at least one strong reference, ARC makes sure that thisPersonis kept in memory and is not deallocated.

由于Person类的新实例被赋值给了reference1变量,所以reference1到Person类的新实例之间建立了一个强引用。正是因为这一个强引用,ARC 会保证Person实例被保持在内存中不被销毁。

If you assign the samePersoninstance to two more variables, two more strong references to that instance are established:

如果你将同一个Person实例也赋值给其他两个变量,该实例又会多出两个强引用:

reference2 = reference1

reference3 = reference1

There are nowthreestrong references to this singlePersoninstance.

现在这一个Person实例已经有三个强引用了。

If you break two of these strong references (including the original reference) by assigningnilto two of the variables, a single strong reference remains, and thePersoninstance is not deallocated:

如果你通过给其中两个变量赋值nil的方式断开两个强引用(包括最先的那个强引用),只留下一个强引用,Person实例不会被销毁:

reference1 = nil

reference2 = nil

ARC does not deallocate thePersoninstance until the third and final strong reference is broken, at which point it is clear that you are no longer using thePersoninstance:

在你清楚地表明不再使用这个Person实例时,即第三个也就是最后一个强引用被断开时,ARC 会销毁它:

reference3=nil

// Prints "John Appleseed is being deinitialized"

Strong Reference Cycles Between Class Instances (类实例之间的循环强引用)

In the examples above, ARC is able to track the number of references to the newPersoninstance you create and to deallocate thatPersoninstance when it is no longer needed.

在上面的例子中,ARC 会跟踪你所新创建的Person实例的引用数量,并且会在Person实例不再被需要时销毁它。

However, it is possible to write code in which an instance of a classnevergets to a point where it has zero strong references. This can happen if two class instances hold a strong reference to each other, such that each instance keeps the other alive. This is known as astrong reference cycle.

然而,我们可能会写出一个类实例的强引用数永远不能变成0的代码。如果两个类实例互相持有对方的强引用,因而每个实例都让对方一直存在,就是这种情况。这就是所谓的循环强引用

You resolve strong reference cycles by defining some of the relationships between classes as weak or unowned references instead of as strong references. This process is described inResolving Strong Reference Cycles Between Class Instances. However, before you learn how to resolve a strong reference cycle, it is useful to understand how such a cycle is caused.

你可以通过定义类之间的关系为弱引用或无主引用,以替代强引用,从而解决循环强引用的问题。具体的过程在解决类实例之间的循环强引用中有描述。不管怎样,在你学习怎样解决循环强引用之前,很有必要了解一下它是怎样产生的。

Here’s an example of how a strong reference cycle can be created by accident. This example defines two classes calledPersonandApartment, which model a block of apartments and its residents:

下面展示了一个不经意产生循环强引用的例子。例子定义了两个类:Person和Apartment,用来建模公寓和它其中的居民:

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}

var tenant:Person?

deinit {print("Apartment\(unit)is being deinitialized") }

}

EveryPersoninstance has anameproperty of typeStringand an optionalapartmentproperty that is initiallynil. Theapartmentproperty is optional, because a person may not always have an apartment.

每一个Person实例有一个类型为String,名字为name的属性,并有一个可选的初始化为nil的apartment属性。apartment属性是可选的,因为一个人并不总是拥有公寓。

Similarly, everyApartmentinstance has aunitproperty of typeStringand has an optionaltenantproperty that is initiallynil. The tenant property is optional because an apartment may not always have a tenant.

类似的,每个Apartment实例有一个叫unit,类型为String的属性,并有一个可选的初始化为nil的tenant属性。tenant属性是可选的,因为一栋公寓并不总是有居民。

Both of these classes also define a deinitializer, which prints the fact that an instance of that class is being deinitialized. This enables you to see whether instances ofPersonandApartmentare being deallocated as expected.

这两个类都定义了析构函数,用以在类实例被析构的时候输出信息。这让你能够知晓Person和Apartment的实例是否像预期的那样被销毁。

This next code snippet defines two variables of optional type calledjohnandunit4A, which will be set to a specificApartmentandPersoninstance below. Both of these variables have an initial value ofnil, by virtue of being optional:

接下来的代码片段定义了两个可选类型的变量john和unit4A,并分别被设定为下面的Apartment和Person的实例。这两个变量都被初始化为nil,这正是可选类型的优点:

var john:Person?

var unit4A:Apartment?

You can now create a specificPersoninstance andApartmentinstance and assign these new instances to thejohnandunit4Avariables:

现在你可以创建特定的Person和Apartment实例并将赋值给john和unit4A变量:

john = Person(name:"John Appleseed")

unit4A = Apartment(unit:"4A")

Here’s how the strong references look after creating and assigning these two instances. Thejohnvariable now has a strong reference to the newPersoninstance, and theunit4Avariable has a strong reference to the newApartmentinstance:

在两个实例被创建和赋值后,下图表现了强引用的关系。变量john现在有一个指向Person实例的强引用,而变量unit4A有一个指向Apartment实例的强引用:

You can now link the two instances together so that the person has an apartment, and the apartment has a tenant. Note that an exclamation mark (!) is used to unwrap and access the instances stored inside thejohnandunit4Aoptional variables, so that the properties of those instances can be set:

现在你能够将这两个实例关联在一起,这样人就能有公寓住了,而公寓也有了房客。注意感叹号是用来展开和访问可选变量john和unit4A中的实例,这样实例的属性才能被赋值:

john!.apartment=unit4A

unit4A!.tenant=john

Here’s how the strong references look after you link the two instances together:

在将两个实例联系在一起之后,强引用的关系如图所示:

Unfortunately, linking these two instances creates a strong reference cycle between them. ThePersoninstance now has a strong reference to theApartmentinstance, and theApartmentinstance has a strong reference to thePersoninstance. Therefore, when you break the strong references held by thejohnandunit4Avariables, the reference counts do not drop to zero, and the instances are not deallocated by ARC:

不幸的是,这两个实例关联后会产生一个循环强引用。Person实例现在有了一个指向Apartment实例的强引用,而Apartment实例也有了一个指向Person实例的强引用。因此,当你断开john和unit4A变量所持有的强引用时,引用计数并不会降为0,实例也不会被 ARC 销毁:

john=nil

unit4A=nil

Note that neither deinitializer was called when you set these two variables tonil. The strong reference cycle prevents thePersonandApartmentinstances from ever being deallocated, causing a memory leak in your app.

注意,当你把这两个变量设为nil时,没有任何一个析构函数被调用。循环强引用会一直阻止Person和Apartment类实例的销毁,这就在你的应用程序中造成了内存泄漏。

Here’s how the strong references look after you set thejohnandunit4Avariables tonil:

在你将john和unit4A赋值为nil后,强引用关系如下图:

The strong references between thePersoninstance and theApartmentinstance remain and cannot be broken.

Person和Apartment实例之间的强引用关系保留了下来并且不会被断开。

Resolving Strong Reference Cycles Between Class Instances (解决实例之间的循环强引用)

Swift provides two ways to resolve strong reference cycles when you work with properties of class type: weak references and unowned references.

Swift 提供了两种办法用来解决你在使用类的属性时所遇到的循环强引用问题:弱引用(weak reference)和无主引用(unowned reference)。

Weak and unowned references enable one instance in a reference cycle to refer to the other instancewithoutkeeping a strong hold on it. The instances can then refer to each other without creating a strong reference cycle.

弱引用和无主引用允许循环引用中的一个实例引用而另外一个实例保持强引用。这样实例能够互相引用而不产生循环强引用。

Use a weak reference when the other instance has a shorter lifetime—that is, when the other instance can be deallocated first. In theApartmentexample above, it is appropriate for an apartment to be able to have no tenant at some point in its lifetime, and so a weak reference is an appropriate way to break the reference cycle in this case. In contrast, use an unowned reference when the other instance has the same lifetime or a longer lifetime.

当其他的实例有更短的生命周期时,使用弱引用,也就是说,当其他实例析构在先时。在上面公寓的例子中,很显然一个公寓在它的生命周期内会在某个时间段没有它的主人,所以一个弱引用就加在公寓类里面,避免循环引用。相比之下,当其他实例有相同的或者更长生命周期时,请使用无主引用。

Weak References (弱引用)

Aweak referenceis a reference that does not keep a strong hold on the instance it refers to, and so does not stop ARC from disposing of the referenced instance. This behavior prevents the reference from becoming part of a strong reference cycle. You indicate a weak reference by placing theweakkeyword before a property or variable declaration.

弱引用不会对其引用的实例保持强引用,因而不会阻止 ARC 销毁被引用的实例。这个特性阻止了引用变为循环强引用。声明属性或者变量时,在前面加上weak关键字表明这是一个弱引用。

Because a weak reference does not keep a strong hold on the instance it refers to, it is possible for that instance to be deallocated while the weak reference is still referring to it. Therefore, ARC automatically sets a weak reference tonilwhen the instance that it refers to is deallocated. And, because weak references need to allow their value to be changed tonilat runtime, they are always declared as variables, rather than constants, of an optional type.

因为弱引用不会保持所引用的实例,即使引用存在,实例也有可能被销毁。因此,ARC 会在引用的实例被销毁后自动将其赋值为nil。并且因为弱引用可以允许它们的值在运行时被赋值为nil,所以它们会被定义为可选类型变量,而不是常量。

You can check for the existence of a value in the weak reference, just like any other optional value, and you will never end up with a reference to an invalid instance that no longer exists.

你可以像其他可选值一样,检查弱引用的值是否存在,你将永远不会访问已销毁的实例的引用。

NOTE

Property observers aren’t called when ARC sets a weak reference tonil.

当 ARC 设置弱引用为nil时,属性观察不会被触发。

The example below is identical to thePersonandApartmentexample from above, with one important difference. This time around, theApartmenttype’stenantproperty is declared as a weak reference:

下面的例子跟上面Person和Apartment的例子一致,但是有一个重要的区别。这一次,Apartment的tenant属性被声明为弱引用:

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") }

}

The strong references from the two variables (johnandunit4A) and the links between the two instances are created as before:

然后跟之前一样,建立两个变量(john和unit4A)之间的强引用,并关联两个实例:

var john:Person?

var unit4A:Apartment?

john=Person(name:"John Appleseed")

unit4A=Apartment(unit:"4A")

john!.apartment=unit4A

unit4A!.tenant=john

Here’s how the references look now that you’ve linked the two instances together:

现在,两个关联在一起的实例的引用关系如下图所示:

ThePersoninstance still has a strong reference to theApartmentinstance, but theApartmentinstance now has aweakreference to thePersoninstance. This means that when you break the strong reference held by thejohnvariable by setting it tonil, there are no more strong references to thePersoninstance:

Person实例依然保持对Apartment实例的强引用,但是Apartment实例只持有对Person实例的弱引用。这意味着当你断开john变量所保持的强引用时,再也没有指向Person实例的强引用了:

john = nil

// Prints "John Appleseed is being deinitialized"

Because there are no more strong references to thePersoninstance, it is deallocated and thetenantproperty is set tonil:

由于再也没有指向Person实例的强引用,该实例会被销毁:

The only remaining strong reference to theApartmentinstance is from theunit4Avariable. If you breakthatstrong reference, there are no more strong references to theApartmentinstance:

唯一剩下的指向Apartment实例的强引用来自于变量unit4A。如果你断开这个强引用,再也没有指向Apartment实例的强引用了:

unit4A=nil

// Prints "Apartment 4A is being deinitialized"

Because there are no more strong references to theApartmentinstance, it too is deallocated:

由于再也没有指向Apartment实例的强引用,该实例也会被销毁:

NOTE

In systems that use garbage collection, weak pointers are sometimes used to implement a simple caching mechanism because objects with no strong references are deallocated only when memory pressure triggers garbage collection. However, with ARC, values are deallocated as soon as their last strong reference is removed, making weak references unsuitable for such a purpose.

在使用垃圾收集的系统里,弱指针有时用来实现简单的缓冲机制,因为没有强引用的对象只会在内存压力触发垃圾收集时才被销毁。但是在 ARC 中,一旦值的最后一个强引用被移除,就会被立即销毁,这导致弱引用并不适合上面的用途。

Unowned References (无主引用)

Like a weak reference, anunowned referencedoes not keep a strong hold on the instance it refers to. Unlike a weak reference, however, an unowned reference is used when the other instance has the same lifetime or a longer lifetime. You indicate an unowned reference by placing theunownedkeyword before a property or variable declaration.

和弱引用类似,无主引用不会牢牢保持住引用的实例。和弱引用不同的是,无主引用在其他实例有相同或者更长的生命周期时使用。你可以在声明属性或者变量时,在前面加上关键字unowned表示这是一个无主引用。

An unowned reference is expected to always have a value. As a result, ARC never sets an unowned reference’s value tonil, which means that unowned references are defined using nonoptional types.

无主引用通常都被期望拥有值。不过 ARC 无法在实例被销毁后将无主引用设为nil,因为非可选类型的变量不允许被赋值为nil。

IMPORTANT

Use an unowned reference only when you are sure that the referencealwaysrefers to an instance that has not been deallocated.

使用无主引用,你必须确保引用始终指向一个未销毁的实例。

If you try to access the value of an unowned reference after that instance has been deallocated, you’ll get a runtime error.

如果你试图在实例被销毁后,访问该实例的无主引用,会触发运行时错误。

The following example defines two classes,CustomerandCreditCard, which model a bank customer and a possible credit card for that customer. These two classes each store an instance of the other class as a property. This relationship has the potential to create a strong reference cycle.

下面的例子定义了两个类,Customer和CreditCard,模拟了银行客户和客户的信用卡。这两个类中,每一个都将另外一个类的实例作为自身的属性。这种关系可能会造成循环强引用。

The relationship betweenCustomerandCreditCardis slightly different from the relationship betweenApartmentandPersonseen in the weak reference example above. In this data model, a customer may or may not have a credit card, but a credit card willalwaysbe associated with a customer. ACreditCardinstance never outlives theCustomerthat it refers to. To represent this, theCustomerclass has an optionalcardproperty, but theCreditCardclass has an unowned (and nonoptional)customerproperty.

Customer和CreditCard之间的关系与前面弱引用例子中Apartment和Person的关系略微不同。在这个数据模型中,一个客户可能有或者没有信用卡,但是一张信用卡总是关联着一个客户。为了表示这种关系,Customer类有一个可选类型的card属性,但是CreditCard类有一个非可选类型的customer属性。

Furthermore, a newCreditCardinstance canonlybe created by passing anumbervalue and acustomerinstance to a customCreditCardinitializer. This ensures that aCreditCardinstance always has acustomerinstance associated with it when theCreditCardinstance is created.

此外,只能通过将一个number值和customer实例传递给CreditCard构造函数的方式来创建CreditCard实例。这样可以确保当创建CreditCard实例时总是有一个customer实例与之关联。

Because a credit card will always have a customer, you define itscustomerproperty as an unowned reference, to avoid a strong reference cycle:

由于信用卡总是关联着一个客户,因此将customer属性定义为无主引用,用以避免循环强引用:

class Customer{

    let name:String

    var card:CreditCard?

    init(name:String) {

    self.name=name

}

deinit{print("\(name)is being deinitialized") }

}

class CreditCard{

    let number:UInt64 

    unowned let customer:Customer

    init(number:UInt64,customer:Customer) {

    self.number=number

    self.customer=customer

}

deinit{print("Card #\(number)is being deinitialized") }

}

NOTE

Thenumberproperty of theCreditCardclass is defined with a type ofUInt64rather thanInt, to ensure that thenumberproperty’s capacity is large enough to store a 16-digit card number on both 32-bit and 64-bit systems.

CreditCard类的number属性被定义为UInt64类型而不是Int类型,以确保number属性的存储量在 32 位和 64 位系统上都能足够容纳 16 位的卡号。

This next code snippet defines an optionalCustomervariable calledjohn, which will be used to store a reference to a specific customer. This variable has an initial value of nil, by virtue of being optional:

下面的代码片段定义了一个叫john的可选类型Customer变量,用来保存某个特定客户的引用。由于是可选类型,所以变量被初始化为nil:

var john:Customer?

You can now create aCustomerinstance, and use it to initialize and assign a newCreditCardinstance as that customer’scardproperty:

现在你可以创建Customer类的实例,用它初始化CreditCard实例,并将新创建的CreditCard实例赋值为客户的card属性:

john=Customer(name:"John Appleseed")

john!.card=CreditCard(number:1234_5678_9012_3456,customer:john!)

Here’s how the references look, now that you’ve linked the two instances:

在你关联两个实例后,它们的引用关系如下图所示:

TheCustomerinstance now has a strong reference to theCreditCardinstance, and theCreditCardinstance has an unowned reference to theCustomerinstance.

Customer实例持有对CreditCard实例的强引用,而CreditCard实例持有对Customer实例的无主引用。

Because of the unownedcustomerreference, when you break the strong reference held by thejohnvariable, there are no more strong references to theCustomerinstance:

由于customer的无主引用,当你断开john变量持有的强引用时,再也没有指向Customer实例的强引用了:

Because there are no more strong references to theCustomerinstance, it is deallocated. After this happens, there are no more strong references to theCreditCardinstance, and it too is deallocated:

由于再也没有指向Customer实例的强引用,该实例被销毁了。其后,再也没有指向CreditCard实例的强引用,该实例也随之被销毁了:

john=nil

// Prints "John Appleseed is being deinitialized"

// Prints "Card #1234567890123456 is being deinitialized"

The final code snippet above shows that the deinitializers for theCustomerinstance andCreditCardinstance both print their “deinitialized” messages after thejohnvariable is set tonil.

最后的代码展示了在john变量被设为nil后Customer实例和CreditCard实例的构造函数都打印出了“销毁”的信息。

NOTE

The examples above show how to usesafeunowned references. Swift also providesunsafeunowned references for cases where you need to disable runtime safety checks—for example, for performance reasons. As with all unsafe operations, you take on the responsiblity for checking that code for safety.

上面的例子展示了如何使用安全的无主引用。对于需要禁用运行时的安全检查的情况(例如,出于性能方面的原因),Swift还提供了不安全的无主引用。与所有不安全的操作一样,你需要负责检查代码以确保其安全性。 

You indicate an unsafe unowned reference by writingunowned(unsafe). If you try to access an unsafe unowned reference after the instance that it refers to is deallocated, your program will try to access the memory location where the instance used to be, which is an unsafe operation.

你可以通过unowned(unsafe)来声明不安全无主引用。如果你试图在实例被销毁后,访问该实例的不安全无主引用,你的程序会尝试访问该实例之前所在的内存地址,这是一个不安全的操作。

Unowned References and Implicitly Unwrapped Optional Properties (无主引用以及隐式解析可选属性)

The examples for weak and unowned references above cover two of the more common scenarios in which it is necessary to break a strong reference cycle.

上面弱引用和无主引用的例子涵盖了两种常用的需要打破循环强引用的场景。

ThePersonandApartmentexample shows a situation where two properties, both of which are allowed to benil, have the potential to cause a strong reference cycle. This scenario is best resolved with a weak reference.

Person和Apartment的例子展示了两个属性的值都允许为nil,并会潜在的产生循环强引用。这种场景最适合用弱引用来解决。

TheCustomerandCreditCardexample shows a situation where one property that is allowed to beniland another property that cannot benilhave the potential to cause a strong reference cycle. This scenario is best resolved with an unowned reference.

Customer和CreditCard的例子展示了一个属性的值允许为nil,而另一个属性的值不允许为nil,这也可能会产生循环强引用。这种场景最适合通过无主引用来解决。

However, there is a third scenario, in whichbothproperties should always have a value, and neither property should ever benilonce initialization is complete. In this scenario, it is useful to combine an unowned property on one class with an implicitly unwrapped optional property on the other class.

然而,存在着第三种场景,在这种场景中,两个属性都必须有值,并且初始化完成后永远不会为nil。在这种场景中,需要一个类使用无主属性,而另外一个类使用隐式解析可选属性。

This enables both properties to be accessed directly (without optional unwrapping) once initialization is complete, while still avoiding a reference cycle. This section shows you how to set up such a relationship.

这使两个属性在初始化完成后能被直接访问(不需要可选展开),同时避免了循环引用。这一节将为你展示如何建立这种关系。

The example below defines two classes,CountryandCity, each of which stores an instance of the other class as a property. In this data model, every country must always have a capital city, and every city must always belong to a country. To represent this, theCountryclass has acapitalCityproperty, and theCityclass has acountryproperty:

下面的例子定义了两个类,Country和City,每个类将另外一个类的实例保存为属性。在这个模型中,每个国家必须有首都,每个城市必须属于一个国家。为了实现这种关系,Country类拥有一个capitalCity属性,而City类有一个country属性:

class Country{

    let name:String

    var capitalCity:City!

    init(name:String,capitalName:String) {

        self.name=name

        self.capitalCity=City(name:capitalName,country:self)

    }

}

class City{

    let name:String

    unowned let country:Country

    init(name:String,country:Country) {

        self.name=name

        self.country=country

    }

}

To set up the interdependency between the two classes, the initializer forCitytakes aCountryinstance, and stores this instance in itscountryproperty.

为了建立两个类的依赖关系,City的构造函数接受一个Country实例作为参数,并且将实例保存到country属性。

The initializer forCityis called from within the initializer forCountry. However, the initializer forCountrycannot passselfto theCityinitializer until a newCountryinstance is fully initialized, as described inTwo-Phase Initialization.

Country的构造函数调用了City的构造函数。然而,只有Country的实例完全初始化后,Country的构造函数才能把self传给City的构造函数。在两段式构造过程中有具体描述。

To cope with this requirement, you declare thecapitalCityproperty ofCountryas an implicitly unwrapped optional property, indicated by the exclamation mark at the end of its type annotation (City!). This means that thecapitalCityproperty has a default value ofnil, like any other optional, but can be accessed without the need to unwrap its value as described inImplicitly Unwrapped Optionals.

为了满足这种需求,通过在类型结尾处加上感叹号(City!)的方式,将Country的capitalCity属性声明为隐式解析可选类型的属性。这意味着像其他可选类型一样,capitalCity属性的默认值为nil,但是不需要展开它的值就能访问它。在隐式解析可选类型中有描述。

BecausecapitalCityhas a defaultnilvalue, a newCountryinstance is considered fully initialized as soon as theCountryinstance sets itsnameproperty within its initializer. This means that theCountryinitializer can start to reference and pass around the implicitselfproperty as soon as thenameproperty is set. TheCountryinitializer can therefore passselfas one of the parameters for theCityinitializer when theCountryinitializer is setting its owncapitalCityproperty.

由于capitalCity默认值为nil,一旦Country的实例在构造函数中给name属性赋值后,整个初始化过程就完成了。这意味着一旦name属性被赋值后,Country的构造函数就能引用并传递隐式的self。Country的构造函数在赋值capitalCity时,就能将self作为参数传递给City的构造函数。

All of this means that you can create theCountryandCityinstances in a single statement, without creating a strong reference cycle, and thecapitalCityproperty can be accessed directly, without needing to use an exclamation mark to unwrap its optional value:

以上的意义在于你可以通过一条语句同时创建Country和City的实例,而不产生循环强引用,并且capitalCity的属性能被直接访问,而不需要通过感叹号来展开它的可选值:

var country=Country(name:"Canada",capitalName:"Ottawa")

print("\(country.name)'s capital city is called\(country.capitalCity.name)")

// Prints "Canada's capital city is called Ottawa"

In the example above, the use of an implicitly unwrapped optional means that all of the two-phase class initializer requirements are satisfied. ThecapitalCityproperty can be used and accessed like a nonoptional value once initialization is complete, while still avoiding a strong reference cycle.

在上面的例子中,使用隐式解析可选值意味着满足了类的构造函数的两个构造阶段的要求。capitalCity属性在初始化完成后,能像非可选值一样使用和存取,同时还避免了循环强引用。

Strong Reference Cycles for Closures (闭包引起的循环强引用)

You saw above how a strong reference cycle can be created when two class instance properties hold a strong reference to each other. You also saw how to use weak and unowned references to break these strong reference cycles.

前面我们看到了循环强引用是在两个类实例属性互相保持对方的强引用时产生的,还知道了如何用弱引用和无主引用来打破这些循环强引用。

A strong reference cycle can also occur if you assign a closure to a property of a class instance, and the body of that closure captures the instance. This capture might occur because the closure’s body accesses a property of the instance, such asself.someProperty, or because the closure calls a method on the instance, such asself.someMethod(). In either case, these accesses cause the closure to “capture”self, creating a strong reference cycle.

循环强引用还会发生在当你将一个闭包赋值给类实例的某个属性,并且这个闭包体中又使用了这个类实例时。这个闭包体中可能访问了实例的某个属性,例如self.someProperty,或者闭包中调用了实例的某个方法,例如self.someMethod()。这两种情况都导致了闭包“捕获”self,从而产生了循环强引用。

This strong reference cycle occurs because closures, like classes, arereference types. When you assign a closure to a property, you are assigning areferenceto that closure. In essence, it’s the same problem as above—two strong references are keeping each other alive. However, rather than two class instances, this time it’s a class instance and a closure that are keeping each other alive.

循环强引用的产生,是因为闭包和类相似,都是引用类型。当你把一个闭包赋值给某个属性时,你是将这个闭包的引用赋值给了属性。实质上,这跟之前的问题是一样的——两个强引用让彼此一直有效。但是,和两个类实例不同,这次一个是类实例,另一个是闭包。

Swift provides an elegant solution to this problem, known as aclosure capture list. However, before you learn how to break a strong reference cycle with a closure capture list, it is useful to understand how such a cycle can be caused.

Swift 提供了一种优雅的方法来解决这个问题,称之为闭包捕获列表(closure capture list)。同样的,在学习如何用闭包捕获列表打破循环强引用之前,先来了解一下这里的循环强引用是如何产生的,这对我们很有帮助。

The example below shows how you can create a strong reference cycle when using a closure that referencesself. This example defines a class calledHTMLElement, which provides a simple model for an individual element within an HTML document:

下面的例子为你展示了当一个闭包引用了self后是如何产生一个循环强引用的。例子中定义了一个叫HTMLElement的类,用一种简单的模型表示 HTML 文档中的一个单独的元素:

class HTMLElement{

    let name:String

    let text:String?

    lazy var asHTML: () ->String= {

    if let text=self.text{

        return"<\(self.name)>\(text)"

    } else {

        return"<\(self.name)/>"

    }

}

init(name:String,text:String? =nil) {

    self.name=name

    self.text=text

}

    deinit{

print("\(name)is being deinitialized")

    }

}

TheHTMLElementclass defines anameproperty, which indicates the name of the element, such as"h1"for a heading element,"p"for a paragraph element, or"br"for a line break element.HTMLElementalso defines an optionaltextproperty, which you can set to a string that represents the text to be rendered within that HTML element.

HTMLElement类定义了一个name属性来表示这个元素的名称,例如代表头部元素的"h1",代表段落的“p”,或者代表换行的“br”。HTMLElement还定义了一个可选属性text,用来设置 HTML 元素呈现的文本。

In addition to these two simple properties, theHTMLElementclass defines a lazy property calledasHTML. This property references a closure that combinesnameandtextinto an HTML string fragment. TheasHTMLproperty is of type() -> String, or “a function that takes no parameters, and returns aStringvalue”.

除了上面的两个属性,HTMLElement还定义了一个lazy属性asHTML。这个属性引用了一个将name和text组合成 HTML 字符串片段的闭包。该属性是Void -> String类型,或者可以理解为“一个没有参数,返回String的函数”。

By default, theasHTMLproperty is assigned a closure that returns a string representation of an HTML tag. This tag contains the optionaltextvalue if it exists, or no text content iftextdoes not exist. For a paragraph element, the closure would return" some text "or"", depending on whether thetextproperty equals"some text"ornil.

默认情况下,闭包赋值给了asHTML属性,这个闭包返回一个代表 HTML 标签的字符串。如果text值存在,该标签就包含可选值text;如果text不存在,该标签就不包含文本。对于段落元素,根据text是“some text”还是nil,闭包会返回" some text "或者""。

TheasHTMLproperty is named and used somewhat like an instance method. However, becauseasHTMLis a closure property rather than an instance method, you can replace the default value of theasHTMLproperty with a custom closure, if you want to change the HTML rendering for a particular HTML element.

可以像实例方法那样去命名、使用asHTML属性。然而,由于asHTML是闭包而不是实例方法,如果你想改变特定 HTML 元素的处理方式的话,可以用自定义的闭包来取代默认值。

For example, theasHTMLproperty could be set to a closure that defaults to some text if thetextproperty isnil, in order to prevent the representation from returning an empty HTML tag:

例如,可以将一个闭包赋值给asHTML属性,这个闭包能在text属性是nil时使用默认文本,这是为了避免返回一个空的 HTML 标签:

let heading=HTMLElement(name:"h1")

let defaultText="some default text"

heading.asHTML= {

    return"<\(heading.name)>\(heading.text??defaultText)"

}

print(heading.asHTML())

// Prints "some default text"

NOTE

TheasHTMLproperty is declared as a lazy property, because it is only needed if and when the element actually needs to be rendered as a string value for some HTML output target. The fact thatasHTMLis a lazy property means that you can refer toselfwithin the default closure, because the lazy property will not be accessed until after initialization has been completed andselfis known to exist.

asHTML声明为lazy属性,因为只有当元素确实需要被处理为 HTML 输出的字符串时,才需要使用asHTML。也就是说,在默认的闭包中可以使用self,因为只有当初始化完成以及self确实存在后,才能访问lazy属性。

TheHTMLElementclass provides a single initializer, which takes anameargument and (if desired) atextargument to initialize a new element. The class also defines a deinitializer, which prints a message to show when anHTMLElementinstance is deallocated.

HTMLElement类只提供了一个构造函数,通过name和text(如果有的话)参数来初始化一个新元素。该类也定义了一个析构函数,当HTMLElement实例被销毁时,打印一条消息。

Here’s how you use theHTMLElementclass to create and print a new instance:

下面的代码展示了如何用HTMLElement类创建实例并打印消息:

var paragraph:HTMLElement? =HTMLElement(name:"p",text:"hello, world")

print(paragraph!.asHTML())

// Prints " hello, world"

NOTE

Theparagraphvariable above is defined as anoptionalHTMLElement, so that it can be set tonilbelow to demonstrate the presence of a strong reference cycle.

上面的paragraph变量定义为可选类型的HTMLElement,因此我们可以赋值nil给它来演示循环强引用。

Unfortunately, theHTMLElementclass, as written above, creates a strong reference cycle between anHTMLElementinstance and the closure used for its defaultasHTMLvalue. Here’s how the cycle looks:

不幸的是,上面写的HTMLElement类产生了类实例和作为asHTML默认值的闭包之间的循环强引用。循环强引用如下图所示:

The instance’sasHTMLproperty holds a strong reference to its closure. However, because the closure refers toselfwithin its body (as a way to referenceself.nameandself.text), the closurecapturesself, which means that it holds a strong reference back to theHTMLElementinstance. A strong reference cycle is created between the two. (For more information about capturing values in a closure, seeCapturing Values.)

实例的asHTML属性持有闭包的强引用。但是,闭包在其闭包体内使用了self(引用了self.name和self.text),因此闭包捕获了self,这意味着闭包又反过来持有了HTMLElement实例的强引用。这样两个对象就产生了循环强引用。(更多关于闭包捕获值的信息,请参考值捕获)。

NOTE

Even though the closure refers toselfmultiple times, it only captures one strong reference to theHTMLElementinstance.

虽然闭包多次使用了self,它只捕获HTMLElement实例的一个强引用。

If you set theparagraphvariable toniland break its strong reference to theHTMLElementinstance, neither theHTMLElementinstance nor its closure are deallocated, because of the strong reference cycle:

如果设置paragraph变量为nil,打破它持有的HTMLElement实例的强引用,HTMLElement实例和它的闭包都不会被销毁,也是因为循环强引用:

paragraph=nil

Note that the message in theHTMLElementdeinitializer is not printed, which shows that theHTMLElementinstance is not deallocated.

注意,HTMLElement的析构函数中的消息并没有被打印,证明了HTMLElement实例并没有被销毁。

Resolving Strong Reference Cycles for Closures (解决闭包引起的循环强引用)

You resolve a strong reference cycle between a closure and a class instance by defining acapture listas part of the closure’s definition. A capture list defines the rules to use when capturing one or more reference types within the closure’s body. As with strong reference cycles between two class instances, you declare each captured reference to be a weak or unowned reference rather than a strong reference. The appropriate choice of weak or unowned depends on the relationships between the different parts of your code.

在定义闭包时同时定义捕获列表作为闭包的一部分,通过这种方式可以解决闭包和类实例之间的循环强引用。捕获列表定义了闭包体内捕获一个或者多个引用类型的规则。跟解决两个类实例间的循环强引用一样,声明每个捕获的引用为弱引用或无主引用,而不是强引用。应当根据代码关系来决定使用弱引用还是无主引用。

NOTE

Swift requires you to writeself.somePropertyorself.someMethod()(rather than justsomePropertyorsomeMethod()) whenever you refer to a member ofselfwithin a closure. This helps you remember that it’s possible to captureselfby accident.

Swift 有如下要求:只要在闭包内使用self的成员,就要用self.someProperty或者self.someMethod()(而不只是someProperty或someMethod())。这提醒你可能会一不小心就捕获了self。

Defining a Capture List (定义捕获列表)

Each item in a capture list is a pairing of theweakorunownedkeyword with a reference to a class instance (such asself) or a variable initialized with some value (such asdelegate = self.delegate!). These pairings are written within a pair of square braces, separated by commas.

捕获列表中的每一项都由一对元素组成,一个元素是weak或unowned关键字,另一个元素是类实例的引用(例如self)或初始化过的变量(如delegate = self.delegate!)。这些项在方括号中用逗号分开。

Place the capture list before a closure’s parameter list and return type if they are provided:

如果闭包有参数列表和返回类型,把捕获列表放在它们前面:

lazy var someClosure: (Int,String) ->String= {

    [unownedself,weakdelegate=self.delegate!] (index:Int,stringToProcess:String) ->Stringin

// closure body goes here

}

If a closure does not specify a parameter list or return type because they can be inferred from context, place the capture list at the very start of the closure, followed by theinkeyword:

如果闭包没有指明参数列表或者返回类型,即它们会通过上下文推断,那么可以把捕获列表和关键字in放在闭包最开始的地方:

lazy var someClosure: () ->String= {

    [unownedself,weakdelegate=self.delegate!]in

// closure body goes here

}

Weak and Unowned References (弱引用和无主引用)

Define a capture in a closure as an unowned reference when the closure and the instance it captures will always refer to each other, and will always be deallocated at the same time.

在闭包和捕获的实例总是互相引用并且总是同时销毁时,将闭包内的捕获定义为无主引用。

Conversely, define a capture as a weak reference when the captured reference may becomenilat some point in the future. Weak references are always of an optional type, and automatically becomenilwhen the instance they reference is deallocated. This enables you to check for their existence within the closure’s body.

相反的,在被捕获的引用可能会变为nil时,将闭包内的捕获定义为弱引用。弱引用总是可选类型,并且当引用的实例被销毁后,弱引用的值会自动置为nil。这使我们可以在闭包体内检查它们是否存在。

NOTE

If the captured reference will never becomenil, it should always be captured as an unowned reference, rather than a weak reference.

如果被捕获的引用绝对不会变为nil,应该用无主引用,而不是弱引用。

An unowned reference is the appropriate capture method to use to resolve the strong reference cycle in theHTMLElementexample from earlier. Here’s how you write theHTMLElementclass to avoid the cycle:

前面的HTMLElement例子中,无主引用是正确的解决循环强引用的方法。这样编写HTMLElement类来避免循环强引用:

class HTMLElement{

    let name:String

    let text:String?

    lazy var asHTML: () ->String= {

        [unowned self ] in

        if let text=self.text{

        return"<\(self.name)>\(text)"

    } else {

        return"<\(self.name)/>"

    }

}

    init(name:String,text:String? =nil) {

        self.name=name

        self.text=text

    }

    deinit{

        print("\(name)is being deinitialized")

    }

}

This implementation ofHTMLElementis identical to the previous implementation, apart from the addition of a capture list within theasHTMLclosure. In this case, the capture list is[unowned self], which means “capture self as an unowned reference rather than a strong reference”.

上面的HTMLElement实现和之前的实现一致,除了在asHTML闭包中多了一个捕获列表。这里,捕获列表是[unowned self],表示“将self捕获为无主引用而不是强引用”。

You can create and print anHTMLElementinstance as before:

和之前一样,我们可以创建并打印HTMLElement实例:

var paragraph:HTMLElement? =HTMLElement(name:"p",text:"hello, world")

print(paragraph!.asHTML())

// Prints " hello, world "

Here’s how the references look with the capture list in place:

使用捕获列表后引用关系如下图所示:

This time, the capture ofselfby the closure is an unowned reference, and does not keep a strong hold on theHTMLElementinstance it has captured. If you set the strong reference from theparagraphvariable tonil, theHTMLElementinstance is deallocated, as can be seen from the printing of its deinitializer message in the example below:

这一次,闭包以无主引用的形式捕获self,并不会持有HTMLElement实例的强引用。如果将paragraph赋值为nil,HTMLElement实例将会被销毁,并能看到它的析构函数打印出的消息:

paragraph=nil

// Prints "p is being deinitialized"

For more information about capture lists, seeCapture Lists.

你可以查看捕获列表章节,获取更多关于捕获列表的信息。

上一篇下一篇

猜你喜欢

热点阅读