How does Swift implement ARC in property attributes? For example, how do I make my String variable use copy instead of strong in Swift?
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.
Automatic Reference Counting manages object life cycles by keeping track of all valid references to an object with an internal retain count. Once all references to an object go out of scope or are cleared, and the retain count thus reaches zero, the object and its underlying memory is automatically freed.
In Swift, memory management is handled by Automatic Reference Counting (ARC). Whenever you create a new instance of a class ARC allocates a chunk of memory to store information about the type of instance and values of stored properties of that instance.
Automatic Reference Counting (ARC) is a memory management attribute used to monitor and manage an application's memory usage. Swift memory management works automatically without control. It automatically allocates or de-allocates memory to allow efficient running of applications.
You can use the @NSCopying
attribute when you want the copy
behaviour from Objective-C.
From the Swift Book:
Apply this attribute to a stored variable property of a class. This attribute causes the property’s setter to be synthesized with a copy of the property’s value—returned by the copyWithZone method—instead of the value of the property itself. The type of the property must conform to the NSCopying protocol.
The NSCopying attribute behaves in a way similar to the Objective-C copy property attribute.
However, in the specific case of String
properties, it's not necessary to do so.
Strings are a value type in Swift. As such, when an existing String
is assigned to a new variable, the variable actually stores a copy of the String, rather than a reference to the existing one.
Swift’s String type is a value type. If you create a new String value, that String value is copied when it is passed to a function or method, or when it is assigned to a constant or variable. In each case, a new copy of the existing String value is created, and the new copy is passed or assigned, not the original version.
So, the @NSCopying
attribute is to be used when you have properties of a reference type that you want to set using the copy behaviour.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With