Swift Automatic Reference Counting (ARC)
Automatic Reference Counting (ARC) is how Swift manages memory for class instances.
It automatically tracks how many references hold each instance; once no references remain, it frees that memory.
The two cases ARC cannot handle are "mutual references" and "closures capturing self", which must be broken manually with weak and unowned.
How ARC works
Each time a class instance is created, ARC records a reference count for it.
Each additional strong reference increments the count; each removed strong reference decrements it; when the count reaches zero, the instance is destroyed and deinit is called.
These increments and decrements are inserted automatically by the compiler; there is no need to write retain or release manually.
Example
import Foundation
class
Runoob
{
let name
:
String
init
(
name
:
String
)
{
self.
name
=
name
(
"(name) created"
)
}
deinit
{
(
"(name) destroyed"
)
}
}
var site
:
Runoob
?
=
Runoob
(
name
:
"Runoob"
)
// Reference count 1
(
"Creation complete"
)
site
=
nil
// Reference count reaches zero, triggering deinit
(
"Set to nil complete"
)
Running the above code produces the following output:
Runoob 被创建
创建完成
Runoob 被销毁
置 nil 完成
Note:ARC applies only to class instances. Structs and enums are value types; their lifetimes are determined by scope and copying, with no reference counting.
Strong references and reference counting
References are strong by default; as long as at least one strong reference remains, the instance is not released.
Setting a variable to nil only removes one reference; if the count has not reached zero, the instance is still alive.
Example
var ref1
:
Runoob
?
=
Runoob
(
name
:
"RUNOOB"
)
// Reference count 1
var ref2
=
ref1
// Reference count 2
var ref3
=
ref1
// Reference count 3
ref1
=
nil
// Reference count 2
ref2
=
nil
// Reference count 1
(
"ref3 still holds the instance"
)
ref3
=
nil
// Reference count 0, instance destroyed
(
"All released"
)
Running the above code produces the following output:
RUNOOB 被创建
还剩 ref3 持有实例
RUNOOB 被销毁
全部释放
deinit can only be called by ARC; it cannot be called manually and cannot throw errors inside.
Strong reference cycles
If two instances hold strong references to each other, their reference counts will never reach zero.
This is a strong reference cycle (retain cycle) and is the most common source of memory leaks in ARC.
Example
class
Person
{
let name
:
String
var apartment
:
Apartment
?
// Strong reference
init
(
name
:
String
)
{
self.
name
=
name
(
"(name) created"
)
}
deinit
{
(
"(name) destroyed"
)
}
}
class
Apartment
{
let unit
:
String
var tenant
:
Person
?
// Also a strong reference, forming a cycle
init
(
unit
:
String
)
{
self.
unit
=
unit
(
"Apartment (unit) created"
)
}
deinit
{
(
"Apartment (unit) destroyed"
)
}
}
var runoob
:
Person
?
=
Person
(
name
:
"Runoob"
)
var unitA
:
Apartment
?
=
Apartment
(
unit
:
"A-101"
)
runoob
!
.
apartment
=
unitA
// Person holds Apartment
unitA
!
.
tenant
=
runoob
// Apartment holds Person
runoob
=
nil
// Set local variables to nil
unitA
=
nil
// Set local variables to nil
(
"The two objects hold each other, both reference counts are still 1, deinit will not execute"
)
Running the above code produces the following output:
Runoob 被创建
公寓 A-101 被创建
两个对象互相持有,引用计数都还是 1,deinit 不会执行
Notice that the output contains no "destroyed", indicating both instances are still in memory.
The way to break the cycle is to change one end of the references to weak or unowned.
Weak references: weak
A weak reference does not increase the reference count, and it automatically becomes nil when the target is released.
Because it can become nil, a weak reference must be an optional declared with var.
Changing Apartment's tenant above to a weak reference breaks the cycle.
Example
// Person's definition is unchanged; only Apartment's tenant is changed to a weak reference
class
Apartment
{
let unit
:
String
weak var tenant
:
Person
?
// Weak reference: does not increase the reference count
init
(
unit
:
String
)
{
self.
unit
=
unit
(
"Apartment (unit) created"
)
}
deinit
{
(
"Apartment (unit) destroyed"
)
}
}
var runoob
:
Person
?
=
Person
(
name
:
"Runoob"
)
var unitA
:
Apartment
?
=
Apartment
(
unit
:
"A-101"
)
runoob
!
.
apartment
=
unitA
// Person strongly references Apartment
unitA
!
.
tenant
=
runoob
// Apartment weakly references Person
runoob
=
nil
// Person has no other strong references and is destroyed
(
"Is the tenant still here: (String(describing: unitA!.tenant))"
)
unitA
=
nil
// Apartment is also destroyed
(
"End"
)
Running the above code produces the following output:
Runoob 被创建
公寓 A-101 被创建
Runoob 被销毁
租客是否还在:nil
公寓 A-101 被销毁
结束
Weak references suit expressing "not an ownership relationship": delegate objects, parent nodes pointing back to children, cache entries, and so on.
Unowned references: unowned
An unowned reference also does not increase the reference count, but it assumes the target always outlives the referrer.
Therefore it can be a let or a non-optional type; the cost is that accessing it after the target is released crashes the program.
The classic scenario is "a credit card always belongs to a customer, and the customer always outlives the card".
Example
class
Customer
{
let name
:
String
var card
:
CreditCard
?
init
(
name
:
String
)
{
self.
name
=
name
(
"Customer (name) created"
)
}
deinit
{
(
"Customer (name) destroyed"
)
}
}
class
CreditCard
{
let number
:
String
unowned let customer
:
Customer
// Unowned reference: the card always belongs to a customer
init
(
number
:
String, customer
:
Customer
)
{
self.
number
=
number
self.
customer
=
customer
(
"Credit card (number) created"
)
}
deinit
{
(
"Credit card (number) destroyed"
)
}
}
var runoob
:
Customer
?
=
Customer
(
name
:
"Runoob"
)
runoob
!
.
card
=
CreditCard
(
number
:
"6222-0000"
, customer
:
runoob
!
)
(
"Card owner: (runoob!.card!.customer.name)"
)
runoob
=
nil
// The customer is released and the card is released along with it, with no reference cycle
(
"End"
)
Running the above code produces the following output:
客户 Runoob 被创建
信用卡 6222-0000 被创建
卡主:Runoob
客户 Runoob 被销毁
信用卡 6222-0000 被销毁
结束
The differences among the three kinds of references can be remembered like this:
| Reference method | Increases the reference count | Declaration requirement | After the target is deallocated | Applicable scenarios |
|---|---|---|---|---|
| Strong reference | Is | No special requirement | The target is not deallocated | Ordinary ownership |
Weak reference weak |
No | Must be var An optional type |
Automatically set to nil |
The target may be deallocated first, as with a delegate |
Unowned reference unowned |
No | can be let, and may be non-optional |
Crashes on access | Target lifetime is no shorter than the referrer's |
Note:When in doubt, use
weak. It adds one extra optional check, but a mistake only yields nil, whereasunowneda mistake crashes outright.
Retain cycles caused by closures
A closure captures the external variables it uses, including self.
If the instance also holds the closure, this forms an "instance → closure → instance" cycle.
Example
class
Reporter
{
let site
:
String
var onFinish
:
(
(
)
String
)
?
// The instance holds the closure
init
(
site
:
String
)
{
self.
site
=
site
}
func prepare
(
)
{
// The closure captures self, and the instance holds the closure → retain cycle
onFinish
=
{
return
"Site: (self.site)"
}
}
deinit
{
(
"Reporter deallocated"
)
}
}
var reporter
:
Reporter
?
=
Reporter
(
site
:
"www.runoob.com"
)
reporter
!
.
prepare
(
)
(
reporter
!
.
onFinish
!
(
)
)
reporter
=
nil
(
"The closure holds self; the instance was not deallocated"
)
Running the above code produces the following output:
站点:www.runoob.com
闭包持有 self,实例没有被销毁
Closures assigned to instance properties, as well as closures in a lazy var that reference self, all fall into this category.
Capture lists and guard let self
The solution is to write a capture list [weak self] at the start of the closure so that the closure does not hold the instance.
Since self becomes an optional, it must be unwrapped before access; the standard form is guard let self else { return }.
Example
// The definition of Reporter is unchanged; only the closure in prepare() changes
func prepare
(
)
{
// Capture list [weak self]: the closure no longer holds the instance
onFinish
=
{
[
weak self
]
in
// Since Swift 5.7 this can be shortened to guard let self
guard let self
else
{
return
"Object deallocated"
}
return
"Site: (self.site)"
}
}
var reporter
:
Reporter
?
=
Reporter
(
site
:
"www.runoob.com"
)
reporter
!
.
prepare
(
)
let closure
=
reporter
!
.
onFinish
!
(
closure
(
)
)
// The instance is still alive
reporter
=
nil
// Release the instance; self in the closure becomes nil
(
closure
(
)
)
// guard let self takes effect and returns safely
Running the above code produces the following output:
站点:www.runoob.com
Reporter 被销毁
对象已释放
guard let self else { return } handles the "self has been deallocated" case up front, preventing later code from accessing an empty object.
In a closure returning Void, write a plain return; in a closure returning a value, return a fallback value.
| Capture list | Relationship between the closure and self | Type of self | Applicable scenarios |
|---|---|---|---|
| Not written | Strong reference, prone to cycles | Self |
Non-escaping closure, or when no cycle can occur |
[weak self] |
Weak reference | Self? |
self may be deallocated before the closure |
[unowned self] |
Unowned reference | Self |
self's lifetime is guaranteed to be no shorter than the closure's |
A capture list is only needed when the closure is stored or escapes the current scope; a closure that runs synchronously and is then discarded cannot cause a cycle.
Common questions
The following questions come up most often when tracking down memory leaks.
When should you write a capture list?
Add a capture list when the closure is held by an instance, or escapes and lives a long time, and the closure uses self.
Conversely, closures passed to synchronously executed functions like map or sorted usually do not need one.
Why do you still need guard let self after adding weak?
Because weak makes self optional, using it directly causes a compile error.
Unwrap it once with guard let self else { return }, and afterwards you can access it like a normal instance.
How to choose between weak and unowned
Use weak when the target may be deallocated first, or when there is no clear relationship between the two lifetimes.
Use unowned only when you can guarantee the target outlives the referrer and you do not want to handle an optional.
Can retain cycles be detected automatically?
The compiler cannot, and neither can ARC. It only handles reference counting, not the relationships between objects.
To investigate, use Xcode's Memory Graph or the Leaks template in Instruments to spot objects that should have been deallocated but never had deinit called.