Files
the-swift-programming-langu…/chapter2/16_Automatic_Reference_Counting.html
2014-06-12 14:58:48 +08:00

989 lines
57 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!DOCTYPE HTML>
<html lang="en-US" manifest="../manifest.appcache">
<head prefix="og: http://ogp.me/ns# book: http://ogp.me/ns/book#">
<meta charset="UTF-8">
<title>《The Swift Programming Language》中文版</title>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<meta name="robots" content="index, follow">
<meta name="author" content="">
<meta name="description" content="Swift 中文翻译组364279588要求对翻译感兴趣">
<meta name="keywords" content="gitbook,github" >
<meta name="generator" content="www.gitbook.io">
<link rel="next" href="../chapter2/17_Optional_Chaining.html" />
<link rel="prev" href="../chapter2/15_Deinitialization.html" />
<meta property="og:title" content="自动引用计数 | The Swift Programming Language 中文版">
<meta property="og:site_name" content="The Swift Programming Language 中文版">
<meta property="og:type" content="book">
<meta property="og:locale" content="en_US">
<meta property="book:author" content="https://github.com/">
<meta property="book:tag" content="GitBook">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<link rel="shortcut icon" href="../gitbook/images/favicon.ico" type="image/x-icon">
</head>
<body>
<link rel="stylesheet" href="../gitbook/style.css">
<div class="book" data-level="2.16" data-basepath=".." data-revision="1402556298428">
<div class="book-header">
<!-- Actions Left -->
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
<a href="https://github.com/null" target="_blank" class="btn pull-left home-bookmark" aria-label="GitHub home"><i class="fa fa-bookmark-o"></i></a>
<a href="#" class="btn pull-left toggle-search" aria-label="Toggle search"><i class="fa fa-search"></i></a>
<span id="font-settings-wrapper">
<a href="#" class="btn pull-left toggle-font-settings" aria-label="Toggle font settings"><i class="fa fa-font"></i>
</a>
<div class="dropdown-menu font-settings">
<div class="dropdown-caret">
<span class="caret-outer"></span>
<span class="caret-inner"></span>
</div>
<div class="btn-group btn-block">
<button id="reduce-font-size" class="btn btn-default">A</button>
<button id="enlarge-font-size" class="btn btn-default">A</button>
</div>
<ul class="list-group font-family-list">
<li class="list-group-item" data-font="0">Serif</li>
<li class="list-group-item" data-font="1">Sans</li>
</ul>
<div class="btn-group btn-group-xs btn-block color-theme-list">
<button type="button" class="btn btn-default" id="color-theme-preview-0" data-theme="0">White</button>
<button type="button" class="btn btn-default" id="color-theme-preview-1" data-theme="1">Sepia</button>
<button type="button" class="btn btn-default" id="color-theme-preview-2" data-theme="2">Night</button>
</div>
</div>
</span>
<!-- Actions Right -->
<a href="#" target="_blank" class="btn pull-right google-plus-sharing-link sharing-link" data-sharing="google-plus" aria-label="Share on Google Plus"><i class="fa fa-google-plus"></i></a>
<a href="#" target="_blank" class="btn pull-right facebook-sharing-link sharing-link" data-sharing="facebook" aria-label="Share on Facebook"><i class="fa fa-facebook"></i></a>
<a href="#" target="_blank" class="btn pull-right twitter-sharing-link sharing-link" data-sharing="twitter" aria-label="Share on Twitter"><i class="fa fa-twitter"></i></a>
<!-- Title -->
<h1>
<i class="fa fa-spinner fa-spin"></i>
<a href="../" >The Swift Programming Language 中文版</a>
</h1>
</div>
<div class="book-summary">
<div class="book-search">
<input type="text" placeholder="Search" class="form-control" />
</div>
<ul class="summary">
<li data-level="0" data-path="index.html">
<a href="../"><i class="fa fa-check"></i></a>
</li>
<li class="chapter " data-level="1" data-path="chapter1/chapter1.html">
<a href="../chapter1/chapter1.html">
<i class="fa fa-check"></i> <b>1.</b> 欢迎使用 Swift
</a>
<ul class="articles">
<li class="chapter " data-level="1.1" data-path="chapter1/01_swift.html">
<a href="../chapter1/01_swift.html">
<i class="fa fa-check"></i> <b>1.1.</b> 关于 Swift
</a>
</li>
<li class="chapter " data-level="1.2" data-path="chapter1/02_a_swift_tour.html">
<a href="../chapter1/02_a_swift_tour.html">
<i class="fa fa-check"></i> <b>1.2.</b> Swift 初见
</a>
</li>
</ul>
</li>
<li class="chapter " data-level="2" data-path="chapter2/chapter2.html">
<a href="../chapter2/chapter2.html">
<i class="fa fa-check"></i> <b>2.</b> Swift 教程
</a>
<ul class="articles">
<li class="chapter " data-level="2.1" data-path="chapter2/01_The_Basics.html">
<a href="../chapter2/01_The_Basics.html">
<i class="fa fa-check"></i> <b>2.1.</b> 基础部分
</a>
</li>
<li class="chapter " data-level="2.2" data-path="chapter2/02_Basic_Operators.html">
<a href="../chapter2/02_Basic_Operators.html">
<i class="fa fa-check"></i> <b>2.2.</b> 基本运算符
</a>
</li>
<li class="chapter " data-level="2.3" data-path="chapter2/03_Strings_and_Characters.html">
<a href="../chapter2/03_Strings_and_Characters.html">
<i class="fa fa-check"></i> <b>2.3.</b> 字符串和字符
</a>
</li>
<li class="chapter " data-level="2.4" data-path="chapter2/04_Collection_Types.html">
<a href="../chapter2/04_Collection_Types.html">
<i class="fa fa-check"></i> <b>2.4.</b> 集合类型
</a>
</li>
<li class="chapter " data-level="2.5" data-path="chapter2/05_Control_Flow.html">
<a href="../chapter2/05_Control_Flow.html">
<i class="fa fa-check"></i> <b>2.5.</b> 控制流
</a>
</li>
<li class="chapter " data-level="2.6" data-path="chapter2/06_Functions.html">
<a href="../chapter2/06_Functions.html">
<i class="fa fa-check"></i> <b>2.6.</b> 函数
</a>
</li>
<li class="chapter " data-level="2.7" data-path="chapter2/07_Closures.html">
<a href="../chapter2/07_Closures.html">
<i class="fa fa-check"></i> <b>2.7.</b> 闭包
</a>
</li>
<li class="chapter " data-level="2.8" data-path="chapter2/08_Enumerations.html">
<a href="../chapter2/08_Enumerations.html">
<i class="fa fa-check"></i> <b>2.8.</b> 枚举
</a>
</li>
<li class="chapter " data-level="2.9" data-path="chapter2/09_Classes_and_Structures.html">
<a href="../chapter2/09_Classes_and_Structures.html">
<i class="fa fa-check"></i> <b>2.9.</b> 类和结构体
</a>
</li>
<li class="chapter " data-level="2.10" data-path="chapter2/10_Properties.html">
<a href="../chapter2/10_Properties.html">
<i class="fa fa-check"></i> <b>2.10.</b> 属性
</a>
</li>
<li class="chapter " data-level="2.11" data-path="chapter2/11_Methods.html">
<a href="../chapter2/11_Methods.html">
<i class="fa fa-check"></i> <b>2.11.</b> 方法
</a>
</li>
<li class="chapter " data-level="2.12" data-path="chapter2/12_Subscripts.html">
<a href="../chapter2/12_Subscripts.html">
<i class="fa fa-check"></i> <b>2.12.</b> 附属脚本
</a>
</li>
<li class="chapter " data-level="2.13" data-path="chapter2/13_Inheritance.html">
<a href="../chapter2/13_Inheritance.html">
<i class="fa fa-check"></i> <b>2.13.</b> 继承
</a>
</li>
<li class="chapter " data-level="2.14" data-path="chapter2/14_Initialization.html">
<a href="../chapter2/14_Initialization.html">
<i class="fa fa-check"></i> <b>2.14.</b> 构造过程
</a>
</li>
<li class="chapter " data-level="2.15" data-path="chapter2/15_Deinitialization.html">
<a href="../chapter2/15_Deinitialization.html">
<i class="fa fa-check"></i> <b>2.15.</b> 析构过程
</a>
</li>
<li class="chapter " data-level="2.16" data-path="chapter2/16_Automatic_Reference_Counting.html">
<a href="../chapter2/16_Automatic_Reference_Counting.html">
<i class="fa fa-check"></i> <b>2.16.</b> 自动引用计数
</a>
</li>
<li class="chapter " data-level="2.17" data-path="chapter2/17_Optional_Chaining.html">
<a href="../chapter2/17_Optional_Chaining.html">
<i class="fa fa-check"></i> <b>2.17.</b> 可选链
</a>
</li>
<li class="chapter " data-level="2.18" data-path="chapter2/18_Type_Casting.html">
<a href="../chapter2/18_Type_Casting.html">
<i class="fa fa-check"></i> <b>2.18.</b> 类型检查
</a>
</li>
<li class="chapter " data-level="2.19" data-path="chapter2/19_Nested_Types.html">
<a href="../chapter2/19_Nested_Types.html">
<i class="fa fa-check"></i> <b>2.19.</b> 类型嵌套
</a>
</li>
<li class="chapter " data-level="2.20" data-path="chapter2/20_Extensions.html">
<a href="../chapter2/20_Extensions.html">
<i class="fa fa-check"></i> <b>2.20.</b> 扩展
</a>
</li>
<li class="chapter " data-level="2.21" data-path="chapter2/21_Protocols.html">
<a href="../chapter2/21_Protocols.html">
<i class="fa fa-check"></i> <b>2.21.</b> 协议
</a>
</li>
<li class="chapter " data-level="2.22" data-path="chapter2/22_Generics.html">
<a href="../chapter2/22_Generics.html">
<i class="fa fa-check"></i> <b>2.22.</b> 泛型
</a>
</li>
<li class="chapter " data-level="2.23" data-path="chapter2/23_Advanced_Operators.html">
<a href="../chapter2/23_Advanced_Operators.html">
<i class="fa fa-check"></i> <b>2.23.</b> 高级操作符
</a>
</li>
</ul>
</li>
<li class="chapter " data-level="3" data-path="chapter3/chapter3.html">
<a href="../chapter3/chapter3.html">
<i class="fa fa-check"></i> <b>3.</b> 语言参考
</a>
<ul class="articles">
<li class="chapter " data-level="3.1" data-path="chapter3/01_About_the_Language_Reference.html">
<a href="../chapter3/01_About_the_Language_Reference.html">
<i class="fa fa-check"></i> <b>3.1.</b> 关于语言参考
</a>
</li>
<li class="chapter " data-level="3.2" data-path="chapter3/02_Lexical_Structure.html">
<a href="../chapter3/02_Lexical_Structure.html">
<i class="fa fa-check"></i> <b>3.2.</b> 词法结构
</a>
</li>
<li class="chapter " data-level="3.3" data-path="chapter3/03_Types.html">
<a href="../chapter3/03_Types.html">
<i class="fa fa-check"></i> <b>3.3.</b> 类型
</a>
</li>
<li class="chapter " data-level="3.4" data-path="chapter3/04_Expressions.html">
<a href="../chapter3/04_Expressions.html">
<i class="fa fa-check"></i> <b>3.4.</b> 表达式
</a>
</li>
<li class="chapter " data-level="3.5" data-path="chapter3/10_Statements.html">
<a href="../chapter3/10_Statements.html">
<i class="fa fa-check"></i> <b>3.5.</b> 语句
</a>
</li>
<li class="chapter " data-level="3.6" data-path="chapter3/05_Declarations.html">
<a href="../chapter3/05_Declarations.html">
<i class="fa fa-check"></i> <b>3.6.</b> 声明
</a>
</li>
<li class="chapter " data-level="3.7" data-path="chapter3/06_Attributes.html">
<a href="../chapter3/06_Attributes.html">
<i class="fa fa-check"></i> <b>3.7.</b> 特性
</a>
</li>
<li class="chapter " data-level="3.8" data-path="chapter3/07_Patterns.html">
<a href="../chapter3/07_Patterns.html">
<i class="fa fa-check"></i> <b>3.8.</b> 模式
</a>
</li>
<li class="chapter " data-level="3.9" data-path="chapter3/08_Generic_Parameters_and_Arguments.html">
<a href="../chapter3/08_Generic_Parameters_and_Arguments.html">
<i class="fa fa-check"></i> <b>3.9.</b> 泛型参数
</a>
</li>
<li class="chapter " data-level="3.10" data-path="chapter3/09_Summary_of_the_Grammar.html">
<a href="../chapter3/09_Summary_of_the_Grammar.html">
<i class="fa fa-check"></i> <b>3.10.</b> 语法总结
</a>
</li>
</ul>
</li>
<li class="divider"></li>
<li>
<a href="http://www.gitbook.io/" target="blank" class="gitbook-link">Generated using GitBook</a>
</li>
<li style="margin-left:15%;"> <iframe src="http://ghbtns.com/github-btn.html?user=numbbbbb&repo=the-swift-programming-language-in-chinese&type=watch&count=true&size=large"
allowtransparency="true" frameborder="0" scrolling="0" width="170" height="30"></iframe></li>
</ul>
</div>
<div class="book-body">
<div class="body-inner">
<div class="page-wrapper" tabindex="-1">
<div class="book-progress">
<div class="bar">
<div class="inner" style="width: 31.57894736842105%;min-width: 28.94736842105263%;"></div>
</div>
<div class="chapters">
<a href="../index.html" title="Introduction" class="chapter done new-chapter" data-progress="0" style="left: 0%;"></a>
<a href="../chapter1/chapter1.html" title="欢迎使用 Swift" class="chapter done new-chapter" data-progress="1" style="left: 2.6315789473684212%;"></a>
<a href="../chapter1/01_swift.html" title="关于 Swift" class="chapter done " data-progress="1.1" style="left: 5.2631578947368425%;"></a>
<a href="../chapter1/02_a_swift_tour.html" title="Swift 初见" class="chapter done " data-progress="1.2" style="left: 7.894736842105263%;"></a>
<a href="../chapter2/chapter2.html" title="Swift 教程" class="chapter done new-chapter" data-progress="2" style="left: 10.526315789473685%;"></a>
<a href="../chapter2/01_The_Basics.html" title="基础部分" class="chapter done " data-progress="2.1" style="left: 13.157894736842104%;"></a>
<a href="../chapter2/10_Properties.html" title="属性" class="chapter done " data-progress="2.10" style="left: 15.789473684210526%;"></a>
<a href="../chapter2/11_Methods.html" title="方法" class="chapter done " data-progress="2.11" style="left: 18.42105263157895%;"></a>
<a href="../chapter2/12_Subscripts.html" title="附属脚本" class="chapter done " data-progress="2.12" style="left: 21.05263157894737%;"></a>
<a href="../chapter2/13_Inheritance.html" title="继承" class="chapter done " data-progress="2.13" style="left: 23.68421052631579%;"></a>
<a href="../chapter2/14_Initialization.html" title="构造过程" class="chapter done " data-progress="2.14" style="left: 26.31578947368421%;"></a>
<a href="../chapter2/15_Deinitialization.html" title="析构过程" class="chapter done " data-progress="2.15" style="left: 28.94736842105263%;"></a>
<a href="../chapter2/16_Automatic_Reference_Counting.html" title="自动引用计数" class="chapter done " data-progress="2.16" style="left: 31.57894736842105%;"></a>
<a href="../chapter2/17_Optional_Chaining.html" title="可选链" class="chapter " data-progress="2.17" style="left: 34.21052631578947%;"></a>
<a href="../chapter2/18_Type_Casting.html" title="类型检查" class="chapter " data-progress="2.18" style="left: 36.8421052631579%;"></a>
<a href="../chapter2/19_Nested_Types.html" title="类型嵌套" class="chapter " data-progress="2.19" style="left: 39.473684210526315%;"></a>
<a href="../chapter2/02_Basic_Operators.html" title="基本运算符" class="chapter " data-progress="2.2" style="left: 42.10526315789474%;"></a>
<a href="../chapter2/20_Extensions.html" title="扩展" class="chapter " data-progress="2.20" style="left: 44.73684210526316%;"></a>
<a href="../chapter2/21_Protocols.html" title="协议" class="chapter " data-progress="2.21" style="left: 47.36842105263158%;"></a>
<a href="../chapter2/22_Generics.html" title="泛型" class="chapter " data-progress="2.22" style="left: 50%;"></a>
<a href="../chapter2/23_Advanced_Operators.html" title="高级操作符" class="chapter " data-progress="2.23" style="left: 52.63157894736842%;"></a>
<a href="../chapter2/03_Strings_and_Characters.html" title="字符串和字符" class="chapter " data-progress="2.3" style="left: 55.26315789473684%;"></a>
<a href="../chapter2/04_Collection_Types.html" title="集合类型" class="chapter " data-progress="2.4" style="left: 57.89473684210526%;"></a>
<a href="../chapter2/05_Control_Flow.html" title="控制流" class="chapter " data-progress="2.5" style="left: 60.526315789473685%;"></a>
<a href="../chapter2/06_Functions.html" title="函数" class="chapter " data-progress="2.6" style="left: 63.1578947368421%;"></a>
<a href="../chapter2/07_Closures.html" title="闭包" class="chapter " data-progress="2.7" style="left: 65.78947368421052%;"></a>
<a href="../chapter2/08_Enumerations.html" title="枚举" class="chapter " data-progress="2.8" style="left: 68.42105263157895%;"></a>
<a href="../chapter2/09_Classes_and_Structures.html" title="类和结构体" class="chapter " data-progress="2.9" style="left: 71.05263157894737%;"></a>
<a href="../chapter3/chapter3.html" title="语言参考" class="chapter new-chapter" data-progress="3" style="left: 73.6842105263158%;"></a>
<a href="../chapter3/01_About_the_Language_Reference.html" title="关于语言参考" class="chapter " data-progress="3.1" style="left: 76.3157894736842%;"></a>
<a href="../chapter3/09_Summary_of_the_Grammar.html" title="语法总结" class="chapter " data-progress="3.10" style="left: 78.94736842105263%;"></a>
<a href="../chapter3/02_Lexical_Structure.html" title="词法结构" class="chapter " data-progress="3.2" style="left: 81.57894736842105%;"></a>
<a href="../chapter3/03_Types.html" title="类型" class="chapter " data-progress="3.3" style="left: 84.21052631578948%;"></a>
<a href="../chapter3/04_Expressions.html" title="表达式" class="chapter " data-progress="3.4" style="left: 86.84210526315789%;"></a>
<a href="../chapter3/10_Statements.html" title="语句" class="chapter " data-progress="3.5" style="left: 89.47368421052632%;"></a>
<a href="../chapter3/05_Declarations.html" title="声明" class="chapter " data-progress="3.6" style="left: 92.10526315789474%;"></a>
<a href="../chapter3/06_Attributes.html" title="特性" class="chapter " data-progress="3.7" style="left: 94.73684210526316%;"></a>
<a href="../chapter3/07_Patterns.html" title="模式" class="chapter " data-progress="3.8" style="left: 97.36842105263158%;"></a>
<a href="../chapter3/08_Generic_Parameters_and_Arguments.html" title="泛型参数" class="chapter " data-progress="3.9" style="left: 100%;"></a>
</div>
</div>
<div class="page-inner">
<section class="normal" id="section-gitbook_150">
<blockquote>
<p>翻译TimothyYe</p>
<p>校对Hawstein</p>
</blockquote>
<h1 id="-">自动引用计数</h1>
<hr>
<p>本页包含内容:</p>
<ul>
<li><a href="#how_arc_works">自动引用计数的工作机制</a></li>
<li><a href="#arc_in_action">自动引用计数实践</a></li>
<li><a href="#strong_reference_cycles_between_class_instances">类实例间的强引用环</a></li>
<li><a href="#resolving_strong_reference_cycles_between_class_instances">类实例间的强引用环分解</a></li>
<li><a href="#strong_reference_cycles_for_closures">闭包的强引用环</a></li>
<li><a href="#resolving_strong_reference_cycles_for_closures">闭包的强引用环分解</a></li>
</ul>
<p>Swift 使用自动引用计数ARC这一机制来跟踪和管理你的应用程序的内存。通常情况下Swift 的内存管理机制会一直起着作用你无须自己来考虑内存的管理。ARC 会在类的实例不再被使用时,自动释放其占用的内存。</p>
<p>然而在少数情况下ARC 为了能帮助你管理内存,需要更多的关于你的代码之间关系的信息。本章描述了这些情况,并且为你示范怎样启用 ARC 来管理你的应用程序的内存。</p>
<blockquote>
<p>注意:</p>
<p>引用计数仅仅应用于类的实例。结构体和枚举类型是值类型,不是引用类型,也不是通过引用的方式存储和传递。</p>
</blockquote>
<p><a name="how_arc_works"></a></p>
<h2 id="-">自动引用计数的工作机制</h2>
<p>当你每次创建一个类的新的实例的时候ARC 会分配一大块内存用来储存实例的信息。内存中会包含实例的类型信息以及这个实例所有相关属性的值。此外当实例不再被使用时ARC 释放实例所占用的内存,并让释放的内存能挪作他用。这确保了不再被使用的实例,不会一直占用内存空间。</p>
<p>然而,当 ARC 收回和释放了正在被使用中的实例,该实例的属性和方法将不能再被访问和调用。实际上,如果你试图访问这个实例,你的应用程序很可能会崩溃。</p>
<p>为了确保使用中的实例不会被销毁ARC 会跟踪和计算每一个实例正在被多少属性常量和变量所引用。哪怕实例的引用数为一ARC都不会销毁这个实例。</p>
<p>为了使之成为可能,无论你将实例赋值给属性,常量或者是变量,属性,常量或者变量,都会对此实例创建强引用。之所以称之为强引用,是因为它会将实例牢牢的保持住,只要强引用还在,实例是不允许被销毁的。</p>
<p><a name="arc_in_action"></a></p>
<h2 id="-">自动引用计数实战</h2>
<p>下面的例子展示了自动引用计数的工作机制。例子以一个简单的<code>Person</code>类开始,并定义了一个叫<code>name</code>的常量属性:</p>
<pre><code> class Person {
let name: String
init(name: String) {
self.name = name
println(&quot;\(name) is being initialized&quot;)
}
deinit {
println(&quot;\(name) is being deinitialized&quot;)
}
}
</code></pre><p><code>Person</code>类有一个构造函数,此构造函数为实例的<code>name</code>属性赋值并打印出信息,以表明初始化过程生效。<code>Person</code>类同时也拥有析构函数,同样会在实例被销毁的时候打印出信息。</p>
<p>接下来的代码片段定义了三个类型为<code>Person?</code>的变量,用来按照代码片段中的顺序,为新的<code>Person</code>实例建立多个引用。由于这些变量是被定义为可选类型Person?而不是Person它们的值会被自动初始化为<code>nil</code>,目前还不会引用到<code>Person</code>类的实例。</p>
<pre><code> var reference1: Person?
var reference2: Person?
var reference3: Person?
</code></pre><p>现在你可以创建<code>Person</code>类的新实例,并且将它赋值给三个变量其中的一个:</p>
<pre><code> reference1 = Person(name: &quot;John Appleseed&quot;)
// prints &quot;John Appleseed is being initialized”
</code></pre><p>应当注意到当你调用<code>Person</code>类的构造函数的时候,&quot;John Appleseed is being initialized”会被打印出来。由此可以确定构造函数被执行。</p>
<p>由于<code>Person</code>类的新实例被赋值给了<code>reference1</code>变量,所以<code>reference1</code><code>Person</code>类的新实例之间建立了一个强引用。正是因为这个强引用ARC 会保证<code>Person</code>实例被保持在内存中不被销毁。</p>
<p>如果你将同样的<code>Person</code>实例也赋值给其他两个变量,该实例又会多出两个强引用:</p>
<pre><code> reference2 = reference1
reference3 = reference1
</code></pre><p>现在这个<code>Person</code>实例已经有三个强引用了。</p>
<p>如果你通过给两个变量赋值<code>nil</code>的方式断开两个强引用()包括最先的那个强引用),只留下一个强引用,<code>Person</code>实例不会被销毁:</p>
<pre><code>reference2 = reference1
reference3 = reference1
</code></pre><p>ARC 会在第三个,也即最后一个强引用被断开的时候,销毁<code>Person</code>实例,这也意味着你不再使用这个<code>Person</code>实例:</p>
<pre><code>reference3 = nil
// prints &quot;John Appleseed is being deinitialized&quot;
</code></pre><p><a name="strong_reference_cycles_between_class_instances"></a></p>
<h2 id="-">类实例之间的循环强引用</h2>
<p>在上面的例子中ARC 会跟踪你所新创建的<code>Person</code>实例的引用数量,并且会在<code>Person</code>实例不再被需要时销毁它。</p>
<p>然而我们可能会写出这样的代码一个类永远不会有0个强引用。这种情况发生在两个类实例互相保持对方的强引用并让对方不被销毁。这就是所谓的循环强引用。</p>
<p>你可以通过定义类之间的关系为弱引用或者无主引用,以此替代强引用,从而解决循环强引用的问题。具体的过程在<a href="#1">解决类实例之间的循环强引用</a>中有描述。不管怎样,在你学习怎样解决循环强引用之前,很有必要了解一下它是怎样产生的。</p>
<p>下面展示了一个不经意产生循环强引用的例子。例子定义了两个类:<code>Person</code><code>Apartment</code>,用来建模公寓和它其中的居民:</p>
<pre><code>class Person {
let name: String
init(name: String) { self.name = name }
var apartment: Apartment?
deinit { println(&quot;\(name) is being deinitialized&quot;) }
}
class Apartment {
let number: Int
init(number: Int) { self.number = number }
var tenant: Person?
deinit { println(&quot;Apartment #\(number) is being deinitialized&quot;) }
}
</code></pre><p>每一个<code>Person</code>实例有一个类型为<code>String</code>,名字为<code>name</code>的属性,并有一个可选的初始化为<code>nil</code><code>apartment</code>属性。<code>apartment</code>属性是可选的,因为一个人并不总是拥有公寓。</p>
<p>类似的,每个<code>Apartment</code>实例有一个叫<code>number</code>,类型为<code>Int</code>的属性,并有一个可选的初始化为<code>nil</code><code>tenant</code>属性。<code>tenant</code>属性是可选的,因为一栋公寓并不总是有居民。</p>
<p>这两个类都定义了析构函数,用以在类实例被析构的时候输出信息。这让你能够知晓<code>Person</code><code>Apartment</code>的实例是否像预期的那样被销毁。</p>
<p>接下来的代码片段定义了两个可选类型的变量<code>john</code><code>number73</code>,并分别被设定为下面的<code>Apartment</code><code>Person</code>的实例。这两个变量都被初始化为<code>nil</code>,并为可选的:</p>
<pre><code>var john: Person?
var number73: Apartment?
</code></pre><p>现在你可以创建特定的<code>Person</code><code>Apartment</code>实例并将类实例赋值给<code>john</code><code>number73</code>变量:</p>
<pre><code>john = Person(name: &quot;John Appleseed&quot;)
number73 = Apartment(number: 73)
</code></pre><p>在两个实例被创建和赋值后,下图表面了强引用的关系。变量<code>john</code>现在有一个指向<code>Person</code>实例的强引用,而变量<code>number73</code>有一个指向<code>Apartment</code>实例的强引用:</p>
<p><img src="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Art/referenceCycle01_2x.png" alt=""></p>
<p>现在你能够将这两个实例关联在一起,这样人就能有公寓住了,而公寓也有了房客。注意感叹号是用来展开和访问可选变量<code>john</code><code>number73</code>中的实例,这样实例的属性才能被赋值:</p>
<pre><code>john!.apartment = number73
number73!.tenant = john
</code></pre><p>在将两个实例联系在一起之后,强引用的关系如图所示:</p>
<p><img src="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Art/referenceCycle02_2x.png" alt=""></p>
<p>不幸的是,将这两个实例关联在一起之后,一个循环强引用被创建了。<code>Person</code>实例现在有了一个指向<code>Apartment</code>实例的强引用,而<code>Apartment</code>实例也有了一个指向<code>Person</code>实例的强引用。因此,当你断开<code>john</code><code>number73</code>变量所持有的强引用时,引用计数并不会降为 0实例也不会被 ARC 销毁:</p>
<pre><code>john = nil
number73 = nil
</code></pre><p>注意,当你把这两个变量设为<code>nil</code>时,没有任何一个析构函数被调用。强引用循环阻止了<code>Person</code><code>Apartment</code>类实例的销毁,并在你的应用程序中造成了内存泄漏。</p>
<p>在你将<code>john</code><code>number73</code>赋值为<code>nil</code>后,强引用关系如下图:</p>
<p><img src="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Art/referenceCycle03_2x.png" alt=""></p>
<p><code>Person</code><code>Apartment</code>实例之间的强引用关系保留了下来并且不会被断开。</p>
<p><a name="resolving_strong_reference_cycles_between_class_instances"></a></p>
<h2 id="-a-name-1-a-"><a name="1">解决实例之间的循环强引用</a></h2>
<p>Swift 提供了两种办法用来解决你在使用类的属性时所遇到的循环强引用问题弱引用weak reference和无主引用unowned reference</p>
<p>弱引用和无主引用允许循环引用中的一个实例引用另外一个实例而不保持强引用。这样实例能够互相引用而不产生循环强引用。</p>
<p>对于生命周期中会变为<code>nil</code>的实例使用弱引用。相反的,对于初始化赋值后再也不会被赋值为<code>nil</code>的实例,使用无主引用。</p>
<h3 id="-">弱引用</h3>
<p>弱引用不会牢牢保持住引用的实例,并且不会阻止 ARC 销毁被引用的实例。这种行为阻止了引用变为循环强引用。声明属性或者变量时,在前面加上<code>weak</code>关键字表明这是一个弱引用。</p>
<p>在实例的生命周期中,如果某些时候引用没有值,那么弱引用可以阻止循环强引用。如果引用总是有值,则可以使用无主引用,在<a href="#2">无主引用</a>中有描述。在上面<code>Apartment</code>的例子中,一个公寓的生命周期中,有时是没有“居民”的,因此适合使用弱引用来解决循环强引用。</p>
<blockquote>
<p>注意:</p>
<p>弱引用必须被声明为变量,表明其值能在运行时被修改。弱引用不能被声明为常量。</p>
</blockquote>
<p>因为弱引用可以没有值,你必须将每一个弱引用声明为可选类型。可选类型是在 Swift 语言中推荐的用来表示可能没有值的类型。</p>
<p>因为弱引用不会保持所引用的实例即使引用存在实例也有可能被销毁。因此ARC 会在引用的实例被销毁后自动将其赋值为<code>nil</code>。你可以像其他可选值一样,检查弱引用的值是否存在,你永远也不会遇到被销毁了而不存在的实例。</p>
<p>下面的例子跟上面<code>Person</code><code>Apartment</code>的例子一致,但是有一个重要的区别。这一次,<code>Apartment</code><code>tenant</code>属性被声明为弱引用:</p>
<pre><code>class Person {
let name: String
init(name: String) { self.name = name }
var apartment: Apartment?
deinit { println(&quot;\(name) is being deinitialized&quot;) }
}
class Apartment {
let number: Int
init(number: Int) { self.number = number }
weak var tenant: Person?
deinit { println(&quot;Apartment #\(number) is being deinitialized&quot;) }
}
</code></pre><p>然后跟之前一样建立两个变量john和number73之间的强引用并关联两个实例</p>
<pre><code>var john: Person?
var number73: Apartment?
john = Person(name: &quot;John Appleseed&quot;)
number73 = Apartment(number: 73)
john!.apartment = number73
number73!.tenant = john
</code></pre><p>现在,两个关联在一起的实例的引用关系如下图所示:</p>
<p><img src="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Art/weakReference01_2x.png" alt=""></p>
<p><code>Person</code>实例依然保持对<code>Apartment</code>实例的强引用,但是<code>Apartment</code>实例只是对<code>Person</code>实例的弱引用。这意味着当你断开<code>john</code>变量所保持的强引用时,再也没有指向<code>Person</code>实例的强引用了:</p>
<p><img src="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Art/weakReference02_2x.png" alt=""></p>
<p>由于再也没有指向<code>Person</code>实例的强引用,该实例会被销毁:</p>
<pre><code>john = nil
// prints &quot;John Appleseed is being deinitialized&quot;
</code></pre><p>唯一剩下的指向<code>Apartment</code>实例的强引用来自于变量<code>number73</code>。如果你断开这个强引用,再也没有指向<code>Apartment</code>实例的强引用了:</p>
<p><img src="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Art/weakReference03_2x.png" alt=""></p>
<p>由于再也没有指向<code>Apartment</code>实例的强引用,该实例也会被销毁:</p>
<pre><code>number73 = nil
// prints &quot;Apartment #73 is being deinitialized&quot;
</code></pre><p>上面的两段代码展示了变量<code>john</code><code>number73</code>在被赋值为<code>nil</code>后,<code>Person</code>实例和<code>Apartment</code>实例的析构函数都打印出“销毁”的信息。这证明了引用循环被打破了。</p>
<h3 id="-a-name-2-a-"><a name="2">无主引用</a></h3>
<p>和弱引用类似无主引用不会牢牢保持住引用的实例。和弱引用不同的是无主引用是永远有值的。因此无主引用总是被定义为非可选类型non-optional type。你可以在声明属性或者变量时在前面加上关键字<code>unowned</code>表示这是一个无主引用。</p>
<p>由于无主引用是非可选类型,你不需要在使用它的时候将它展开。无主引用总是可以被直接访问。不过 ARC 无法在实例被销毁后将无主引用设为<code>nil</code>,因为非可选类型的变量不允许被赋值为<code>nil</code></p>
<blockquote>
<p>注意:
如果你试图在实例被销毁后,访问该实例的无主引用,会触发运行时错误。使用无主引用,你必须确保引用始终指向一个未销毁的实例。</p>
<p>还需要注意的是如果你试图访问实例已经被销毁的无主引用,程序会直接崩溃,而不会发生无法预期的行为。所以你应当避免这样的事情发生。</p>
</blockquote>
<p>下面的例子定义了两个类,<code>Customer</code><code>CreditCard</code>,模拟了银行客户和客户的信用卡。这两个类中,每一个都将另外一个类的实例作为自身的属性。这种关系会潜在的创造循环强引用。</p>
<p><code>Customer</code><code>CreditCard</code>之间的关系与前面弱引用例子中<code>Apartment</code><code>Person</code>的关系截然不同。在这个数据模型中,一个客户可能有或者没有信用卡,但是一张信用卡总是关联着一个客户。为了表示这种关系,<code>Customer</code>类有一个可选类型的<code>card</code>属性,但是<code>CreditCard</code>类有一个非可选类型的<code>customer</code>属性。</p>
<p>此外,只能通过将一个<code>number</code>值和<code>customer</code>实例传递给<code>CreditCard</code>构造函数的方式来创建<code>CreditCard</code>实例。这样可以确保当创建<code>CreditCard</code>实例时总是有一个<code>customer</code>实例与之关联。</p>
<p>由于信用卡总是关联着一个客户,因此将<code>customer</code>属性定义为无主引用,用以避免循环强引用:</p>
<pre><code>class Customer {
let name: String
var card: CreditCard?
init(name: String) {
self.name = name
}
deinit { println(&quot;\(name) is being deinitialized&quot;) }
}
class CreditCard {
let number: Int
unowned let customer: Customer
init(number: Int, customer: Customer) {
self.number = number
self.customer = customer
}
deinit { println(&quot;Card #\(number) is being deinitialized&quot;) }
}
</code></pre><p>下面的代码片段定义了一个叫<code>john</code>的可选类型<code>Customer</code>变量,用来保存某个特定客户的引用。由于是可选类型,所以变量被初始化为<code>nil</code></p>
<pre><code>var john: Customer?
</code></pre><p>现在你可以创建<code>Customer</code>类的实例,用它初始化<code>CreditCard</code>实例,并将新创建的<code>CreditCard</code>实例赋值为客户的<code>card</code>属性。</p>
<pre><code>john = Customer(name: &quot;John Appleseed&quot;)
john!.card = CreditCard(number: 1234_5678_9012_3456, customer: john!)
</code></pre><p>在你关联两个实例后,他们的引用关系如下图所示:</p>
<p><img src="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Art/unownedReference01_2x.png" alt=""></p>
<p><code>Customer</code>实例持有对<code>CreditCard</code>实例的强引用,而<code>CreditCard</code>实例持有对<code>Customer</code>实例的无主引用。</p>
<p>由于<code>customer</code>的无主引用,当你断开<code>john</code>变量持有的强引用时,再也没有指向<code>Customer</code>实例的强引用了:</p>
<p><img src="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Art/unownedReference02_2x.png" alt=""></p>
<p>由于再也没有指向<code>Customer</code>实例的强引用,该实例被销毁了。其后,再也没有指向<code>CreditCard</code>实例的强引用,该实例也随之被销毁了:</p>
<pre><code>john = nil
// prints &quot;John Appleseed is being deinitialized&quot;
// prints &quot;Card #1234567890123456 is being deinitialized&quot;
</code></pre><p>最后的代码展示了在<code>john</code>变量被设为<code>nil</code><code>Customer</code>实例和<code>CreditCard</code>实例的构造函数都打印出了“销毁”的信息。</p>
<h3 id="-">无主引用以及显式展开的可选属性</h3>
<p>上面弱引用和无主引用的例子涵盖了两种常用的需要打破循环强引用的场景。</p>
<p><code>Person</code><code>Apartment</code>的例子展示了两个属性的值都允许为<code>nil</code>,并会潜在的产生循环强引用。这种场景最适合用弱引用来解决。</p>
<p><code>Customer</code><code>CreditCard</code>的例子展示了一个属性的值允许为<code>nil</code>,而另一个属性的值不允许为<code>nil</code>,并会潜在的产生循环强引用。这种场景最适合通过无主引用来解决。</p>
<p>然而,存在着第三种场景,在这种场景中,两个属性都必须有值,并且初始化完成后不能为<code>nil</code>。在这种场景中,需要一个类使用无主属性,而另外一个类使用显示展开的可选属性。</p>
<p>这使两个属性在初始化完成后能被直接访问(不需要可选展开),同时避免了循环引用。这一节将为你展示如何建立这种关系。</p>
<p>下面的例子定义了两个类,<code>Country</code><code>City</code>,每个类将另外一个类的实例保存为属性。在这个模型中,每个国家必须有首都,而每一个城市必须属于一个国家。为了实现这种关系,<code>Country</code>类拥有一个<code>capitalCity</code>属性,而<code>City</code>类有一个<code>country</code>属性:</p>
<pre><code>class Country {
let name: String
let 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
}
}
</code></pre><p>为了建立两个类的依赖关系,<code>City</code>的构造函数有一个<code>Country</code>实例的参数,并且将实例保存为<code>country</code>属性。</p>
<p><code>Country</code>的构造函数调用了<code>City</code>的构造函数。然而,只有<code>Country</code>的实例完全初始化完后,<code>Country</code>的构造函数才能把<code>self</code>传给<code>City</code>的构造函数。(<a href="14_Initialization.html">在两步构造函数中有具体描述</a></p>
<p>为了满足这种需求通过在类型结尾处加上感叹号City!)的方式,将<code>Country</code><code>capitalCity</code>属性声明为显示展开的可选类型属性。这表示像其他可选类型一样,<code>capitalCity</code>属性的默认值为<code>nil</code>,但是不需要展开他的值就能访问它。(<a href="01_The_Basics.html">在显示展开的可选类型中有描述</a></p>
<p>由于<code>capitalCity</code>默认值为<code>nil</code>,一旦<code>Country</code>的实例在构造函数中给<code>name</code>属性赋值后,整个初始化过程就完成了。这代表一旦<code>name</code>属性被后,<code>Country</code>的构造函数就能引用并传递显式的<code>self</code><code>Country</code>的构造函数在赋值<code>capitalCity</code>时,就能将<code>self</code>作为参数传递给<code>City</code>的构造函数。</p>
<p>以上的意义在于你可以通过一条语句同时创建<code>Country</code><code>City</code>的实例,而不产生循环强引用,并且<code>capitalCity</code>的属性能被直接访问,而不需要通过感叹号来展开它的可选值:</p>
<pre><code>var country = Country(name: &quot;Canada&quot;, capitalName: &quot;Ottawa&quot;)
println(&quot;\(country.name)&#39;s capital city is called \(country.capitalCity.name)&quot;)
// prints &quot;Canada&#39;s capital city is called Ottawa&quot;
</code></pre><p>在上面的例子中,使用显示展开可选值的意义在于满足了两个类构造函数的需求。<code>capitalCity</code>属性在初始化完成后,能作为非可选值使用同事还避免了循环强引用。</p>
<p><a name="strong_reference_cycles_for_closures"></a></p>
<h2 id="-">闭包引起的循环强引用</h2>
<p>前面我们看到了循环强引用环是在两个类实例属性互相保持对方的强引用时产生的,还知道了如何用弱引用和无主引用来打破循环强引用。</p>
<p>循环强引用还会发生在当你将一个闭包赋值给类实例的某个属性,并且这个闭包体中又使用了实例。这个闭包体中可能访问了实例的某个属性,例如<code>self.someProperty</code>,或者闭包中调用了实例的某个方法,例如<code>self.someMethod</code>。这两种情况都导致了闭包 “捕获&quot; <code>self</code>,从而产生了循环强引用。</p>
<p>循环强引用的产生,是因为闭包和类相似,都是引用类型。当你把一个闭包赋值给某个属性时,你也把一个引用赋值给了这个闭包。实质上,这跟之前的问题是一样的-两个强引用让彼此一直有效。但是,和两个类实例不同,这次一个是类实例,另一个是闭包。</p>
<p>Swift 提供了一种优雅的方法来解决这个问题称之为闭包占用列表closuer capture list。同样的在学习如何用闭包占用列表破坏循环强引用之前先来了解一下循环强引用是如何产生的这对我们是很有帮助的。</p>
<p>下面的例子为你展示了当一个闭包引用了<code>self</code>后是如何产生一个循环强引用的。例子中定义了一个叫<code>HTMLElement</code>的类,用一种简单的模型表示 HTML 中的一个单独的元素:</p>
<pre><code>class HTMLElement {
let name: String
let text: String?
@lazy var asHTML: () -&gt; String = {
if let text = self.text {
return &quot;&lt;\(self.name)&gt;\(text)&lt;/\(self.name)&gt;&quot;
} else {
return &quot;&lt;\(self.name) /&gt;&quot;
}
}
init(name: String, text: String? = nil) {
self.name = name
self.text = text
}
deinit {
println(&quot;\(name) is being deinitialized&quot;)
}
}
</code></pre><p><code>HTMLElement</code>类定义了一个<code>name</code>属性来表示这个元素的名称,例如代表段落的&quot;p&quot;,或者代表换行的&quot;br&quot;<code>HTMLElement</code>还定义了一个可选属性<code>text</code>,用来设置和展现 HTML 元素的文本。</p>
<p>除了上面的两个属性,<code>HTMLElement</code>还定义了一个<code>lazy</code>属性<code>asHTML</code>。这个属性引用了一个闭包,将<code>name</code><code>text</code>组合成 HTML 字符串片段。该属性是<code>() -&gt; String</code>类型,或者可以理解为“一个没有参数,返回<code>String</code>的函数”。</p>
<p>默认情况下,闭包赋值给了<code>asHTML</code>属性,这个闭包返回一个代表 HTML 标签的字符串。如果<code>text</code>值存在,该标签就包含可选值<code>text</code>;如果<code>text</code>不存在,该标签就不包含文本。对于段落元素,根据<code>text</code>&quot;some text&quot;还是<code>nil</code>,闭包会返回&quot;<code>&lt;p&gt;some text&lt;/p&gt;</code>&quot;或者&quot;<code>&lt;p /&gt;</code>&quot;</p>
<p>可以像实例方法那样去命名、使用<code>asHTML</code>属性。然而,由于<code>asHTML</code>是闭包而不是实例方法,如果你想改变特定元素的 HTML 处理的话,可以用自定义的闭包来取代默认值。</p>
<blockquote>
<p>注意:</p>
<p><code>asHTML</code>声明为<code>lazy</code>属性因为只有当元素确实需要处理为HTML输出的字符串时才需要使用<code>asHTML</code>。也就是说,在默认的闭包中可以使用<code>self</code>,因为只有当初始化完成以及<code>self</code>确实存在后,才能访问<code>lazy</code>属性。</p>
</blockquote>
<p><code>HTMLElement</code>类只提供一个构造函数,通过<code>name</code><code>text</code>(如果有的话)参数来初始化一个元素。该类也定义了一个析构函数,当<code>HTMLElement</code>实例被销毁时,打印一条消息。</p>
<p>下面的代码展示了如何用<code>HTMLElement</code>类创建实例并打印消息。</p>
<pre><code>var paragraph: HTMLElement? = HTMLElement(name: &quot;p&quot;, text: &quot;hello, world&quot;)
println(paragraph!.asHTML())
// prints&quot;hello, world&quot;
</code></pre><blockquote>
<p>注意:</p>
<p>上面的<code>paragraph</code>变量定义为<code>可选HTMLElement</code>,因此我们可以赋值<code>nil</code>给它来演示循环强引用。</p>
</blockquote>
<p>不幸的是,上面写的<code>HTMLElement</code>类产生了类实例和<code>asHTML</code>默认值的闭包之间的循环强引用。循环强引用如下图所示:</p>
<p><img src="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Art/closureReferenceCycle01_2x.png" alt=""></p>
<p>实例的<code>asHTML</code>属性持有闭包的强引用。但是,闭包在其闭包体内使用了<code>self</code>(引用了<code>self.name</code><code>self.text</code>),因此闭包占有了<code>self</code>,这意味着闭包又反过来持有了<code>HTMLElement</code>实例的强引用。这样两个对象就产生了循环强引用。(更多关于闭包占有值的信息,请参考<a href="07_Closures.html">值捕获</a>)。</p>
<blockquote>
<p>注意:</p>
<p>虽然闭包多次使用了<code>self</code>,它只占有<code>HTMLElement</code>实例的一个强引用。</p>
</blockquote>
<p>如果设置<code>paragraph</code>变量为<code>nil</code>,打破它持有的<code>HTMLElement</code>实例的强引用,<code>HTMLElement</code>实例和它的闭包都不会被销毁,也是因为循环强引用:</p>
<pre><code>paragraph = nil
</code></pre><p>注意<code>HTMLElementdeinitializer</code>中的消息并没有别打印,证明了<code>HTMLElement</code>实例并没有被销毁。</p>
<h2 id="-">解决闭包引起的循环强引用</h2>
<p>在定义闭包时同时定义占有列表作为闭包的一部分,通过这种方式可以解决闭包和类实例之间的循环强引用。占有列表定义了闭包体内占有一个或者多个引用类型的规则。跟解决两个类实例间的循环强引用一样,声明每个占有的引用为弱引用或无主引用,而不是强引用。应当根据代码关系来决定使用弱引用还是无主引用。</p>
<blockquote>
<p>注意:</p>
<p>Swift 有如下要求:只要在闭包内使用<code>self</code>的成员,就要用<code>self.someProperty</code>或者<code>self.someMethod</code>(而不只是<code>someProperty</code><code>someMethod</code>)。这提醒你可能会不小心就占有了<code>self</code></p>
</blockquote>
<h3 id="-">定义占有列表</h3>
<p>占有列表中的每个元素都是由<code>weak</code>或者<code>unowned</code>关键字和实例的引用(如<code>self</code><code>someInstance</code>)成对组成。每一对都在花括号中,通过逗号分开。</p>
<p>占有列表放置在闭包参数列表和返回类型之前:</p>
<pre><code>@lazy var someClosure: (Int, String) -&gt; String = {
[unowned self] (index: Int, stringToProcess: String) -&gt; String in
// closure body goes here
}
</code></pre><p>如果闭包没有指定参数列表或者返回类型,则可以通过上下文推断,那么可以占有列表放在闭包开始的地方,跟着是关键字<code>in</code></p>
<pre><code>@lazy var someClosure: () -&gt; String = {
[unowned self] in
// closure body goes here
}
</code></pre><h3 id="-">弱引用和无主引用</h3>
<p>当闭包和占有的实例总是互相引用时并且总是同时销毁时,将闭包内的占有定义为无主引用。</p>
<p>相反的,当占有引用有时可能会是<code>nil</code>时,将闭包内的占有定义为弱引用。弱引用总是可选类型,并且当引用的实例被销毁后,弱引用的值会自动置为<code>nil</code>。这使我们可以在闭包内检查他们是否存在。</p>
<blockquote>
<p>注意:</p>
<p>如果占有的引用绝对不会置为<code>nil</code>,应该用无主引用,而不是弱引用。</p>
</blockquote>
<p>前面的<code>HTMLElement</code>例子中,无主引用是正确的解决循环强引用的方法。这样这样编写<code>HTMLElement</code>类来避免循环强引用:</p>
<pre><code>class HTMLElement {
let name: String
let text: String?
@lazy var asHTML: () -&gt; String = {
[unowned self] in
if let text = self.text {
return &quot;&lt;\(self.name)&gt;\(text)&lt;/\(self.name)&gt;&quot;
} else {
return &quot;&lt;\(self.name) /&gt;&quot;
}
}
init(name: String, text: String? = nil) {
self.name = name
self.text = text
}
deinit {
println(&quot;\(name) is being deinitialized&quot;)
}
}
</code></pre><p>上面的<code>HTMLElement</code>实现和之前的实现一致,只是在<code>asHTML</code>闭包中多了一个占有列表。这里,占有列表是<code>[unowned self]</code>,表示“用无主引用而不是强引用来占有<code>self</code>”。</p>
<p>和之前一样,我们可以创建并打印<code>HTMLElement</code>实例:</p>
<pre><code>var paragraph: HTMLElement? = HTMLElement(name: &quot;p&quot;, text: &quot;hello, world&quot;)
println(paragraph!.asHTML())
// prints &quot;&lt;p&gt;hello, world&lt;/p&gt;&quot;
</code></pre><p>使用占有列表后引用关系如下图所示:</p>
<p><img src="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Art/closureReferenceCycle02_2x.png" alt=""></p>
<p>这一次,闭包以无主引用的形式占有<code>self</code>,并不会持有<code>HTMLElement</code>实例的强引用。如果将<code>paragraph</code>赋值为<code>nil</code><code>HTMLElement</code>实例将会被销毁,并能看到它的析构函数打印出的消息。</p>
<pre><code>paragraph = nil
// prints &quot;p is being deinitialized&quot;
</code></pre>
</section>
</div>
</div>
</div>
<a href="../chapter2/15_Deinitialization.html" class="navigation navigation-prev " aria-label="Previous page: 析构过程"><i class="fa fa-angle-left"></i></a>
<a href="../chapter2/17_Optional_Chaining.html" class="navigation navigation-next " aria-label="Next page: 可选链"><i class="fa fa-angle-right"></i></a>
</div>
</div>
<script src="http://cdn.bootcss.com/ace/1.1.3/ace.js"></script>
<script src="http://cdn.bootcss.com/ace/1.1.3/mode-javascript.js"></script>
<script src="../gitbook/jsrepl/jsrepl.js" id="jsrepl-script"></script>
<script src="../gitbook/app.js"></script>
<script src="../gitbook/plugins/gitbook-plugin-mixpanel/plugin.js"></script>
<script src="http://cdn.mathjax.org/mathjax/2.0-latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script src="../gitbook/plugins/gitbook-plugin-mathjax/plugin.js"></script>
<script>
require(["gitbook"], function(gitbook) {
var config = {};
gitbook.start(config);
});
</script>
<script src="http://s19.cnzz.com/z_stat.php?id=1000480711&web_id=1000480711" language="JavaScript"></script></body>
</html>