Swift strong, weak, unowned reference
[Objective-C property attributes]
ARC
- Automatic Reference Counting
is a mechanism which manages a memory, which is applicable for reference
type[About]. An object is deallocated only when there are 0 references on it.
Strong reference
- is set by default and it is safe to use this type in a linear relationships(there is no loop)
Retain cycle
- it is a situation when each of who objects has a strong reference on each other
Break a Retain cycle
: weak
and unowned
. Both of them does not increase an object's retain count by +1
, and have next differences
Weak reference
- When a references object is deallocated(is nil
), ARC
set a weak
reference to nil
too. That is why weak
reference is a variable var
(can not be a constant let
)[var vs let] and that is why it is an optional
weak var delegate: <Type>?
GENERAL
unowned
- When a references object is deallocated(is nil
), the unowned
does not become a nil
because ARC
does not set it. That is why unowned
reference is non-optional
unowned(by default)
safe unowned
- uses runtime safety check
to throw an exception if unowned
reference was deallocated.
Fatal error: Attempted to read an unowned reference but object 0x7fa5dad3f0f0 was already deallocated
unowned(unsafe)
unowned(unsafe)
operates by UnsafePointer
that can create a dangling pointer
. __unsafe_unretained
from Objective-C
. It is a kind of direct memory access which ARC
does not handle. It can produce unexpected behaviour, not just some crash. It has better performance
EXC_BAD_ACCESS
[EXC_BAD_ACCESS]
[Closure sample]