HOME

TheInfoList



OR:

Automatic Reference Counting (ARC) is a
memory management Memory management (also dynamic memory management, dynamic storage allocation, or dynamic memory allocation) is a form of Resource management (computing), resource management applied to computer memory. The essential requirement of memory manag ...
feature of the
Clang Clang () is a compiler front end for the programming languages C, C++, Objective-C, Objective-C++, and the software frameworks OpenMP, OpenCL, RenderScript, CUDA, SYCL, and HIP. It acts as a drop-in replacement for the GNU Compiler ...
compiler In computing, a compiler is a computer program that Translator (computing), translates computer code written in one programming language (the ''source'' language) into another language (the ''target'' language). The name "compiler" is primaril ...
providing automatic
reference counting In computer science, reference counting is a programming technique of storing the number of references, pointers, or handles to a resource, such as an object, a block of memory, disk space, and others. In garbage collection algorithms, refere ...
for the
Objective-C Objective-C is a high-level general-purpose, object-oriented programming language that adds Smalltalk-style message passing (messaging) to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was ...
and
Swift Swift or SWIFT most commonly refers to: * SWIFT, an international organization facilitating transactions between banks ** SWIFT code * Swift (programming language) * Swift (bird), a family of birds It may also refer to: Organizations * SWIF ...
programming language A programming language is a system of notation for writing computer programs. Programming languages are described in terms of their Syntax (programming languages), syntax (form) and semantics (computer science), semantics (meaning), usually def ...
s. At compile time, it inserts into the
object code In computing, object code or object module is the product of an assembler or compiler In computing, a compiler is a computer program that Translator (computing), translates computer code written in one programming language (the ''source'' ...
message A message is a unit of communication that conveys information from a sender to a receiver. It can be transmitted through various forms, such as spoken or written words, signals, or electronic data, and can range from simple instructions to co ...
s retain and release which increase and decrease the reference count at run time, marking for deallocation those
object Object may refer to: General meanings * Object (philosophy), a thing, being, or concept ** Object (abstract), an object which does not exist at any particular time or place ** Physical object, an identifiable collection of matter * Goal, an a ...
s when the number of references to them reaches zero. ARC differs from
tracing garbage collection In computer programming, tracing garbage collection is a form of automatic memory management that consists of determining which objects should be deallocated ("garbage collected") by tracing which objects are ''reachable'' by a chain of referenc ...
in that there is no background process that deallocates the objects asynchronously at runtime. Unlike tracing garbage collection, ARC does not handle
reference cycle In computer science, reference counting is a programming technique of storing the number of Reference (computer science), references, Pointer (computer programming), pointers, or Handle (computing), handles to a resource, such as an object, a bl ...
s automatically. This means that as long as there are "strong" references to an object, it will not be deallocated. Strong cross-references can accordingly create
deadlock Deadlock commonly refers to: * Deadlock (computer science), a situation where two processes are each waiting for the other to finish * Deadlock (locksmithing) or deadbolt, a physical door locking mechanism * Political deadlock or gridlock, a si ...
s and
memory leak In computer science, a memory leak is a type of resource leak that occurs when a computer program incorrectly manages memory allocations in a way that memory which is no longer needed is not released. A memory leak may also happen when an objec ...
s. It is up to the developer to break cycles by using
weak reference In computer programming, a weak reference is a reference that does not protect the referenced object from collection by a garbage collector, unlike a strong reference. An object referenced ''only'' by weak references – meaning "every chain of re ...
s.
Apple Inc. Apple Inc. is an American multinational corporation and technology company headquartered in Cupertino, California, in Silicon Valley. It is best known for its consumer electronics, software, and services. Founded in 1976 as Apple Comput ...
deploys ARC in their operating systems, such as
macOS macOS, previously OS X and originally Mac OS X, is a Unix, Unix-based operating system developed and marketed by Apple Inc., Apple since 2001. It is the current operating system for Apple's Mac (computer), Mac computers. With ...
() and
iOS Ios, Io or Nio (, ; ; locally Nios, Νιός) is a Greek island in the Cyclades group in the Aegean Sea. Ios is a hilly island with cliffs down to the sea on most sides. It is situated halfway between Naxos and Santorini. It is about long an ...
. Limited support (ARCLite) has been available since Snow Leopard and
iOS 4 iOS 4 is the fourth major release of the iOS mobile operating system developed by Apple Inc., being the successor to iPhone OS 3. It was announced at the Apple Special Event on April 8, 2010, and released on June 21, 2010. iOS 4 was the first ...
, with complete support following in Lion and
iOS 5 iOS 5 is the iOS version history, fifth major release of the iOS mobile operating system developed by Apple Inc., being the successor to iOS 4. It was announced at the company's Worldwide Developers Conference on June 6, 2011, and was released ...
. Garbage collection was declared deprecated in Mountain Lion, in favor of ARC, and removed from the Objective-C
runtime library A runtime library is a library that provides access to the runtime environment that is available to a computer program tailored to the host platform. A runtime environment implements the execution model as required for a development environme ...
in
macOS Sierra macOS Sierra (version 10.12) is the thirteenth major release of macOS (formerly known as and ), Apple Inc.'s desktop and server operating system for Macintosh computers. The name "macOS" stems from the intention to unify the operating syst ...
.


Objective-C

The following rules are enforced by the compiler when ARC is turned on: * retain, release, retainCount, autorelease or dealloc cannot be sent to objects. Instead, the compiler inserts these messages at compile time automatically, including uper dealloc/code> when dealloc is overridden. // Without ARC - (void)dealloc // With ARC - (void)dealloc * Programs cannot cast directly between id and void *. This includes casting between Foundation objects and Core Foundation objects. Programs must use special casts, or calls to special functions, to tell the compiler more information about an object's lifetime. // Without ARC - (NSString *)giveMeAString // With ARC - (NSString *)giveMeAString * An autorelease pool can be used to allocate objects temporarily and retain them in memory until the pool is "drained". Without ARC, an NSAutoreleasePool object can be created for this purpose. ARC uses @autoreleasepool blocks instead, which encapsulate the allocation of the temporary objects and deallocates them when the end of the block is reached. // Without ARC - (void)loopThroughArray:(NSArray *)array // With ARC - (void)loopThroughArray:(NSArray *)array * Programs cannot call the functions NSAllocateObject and NSDeallocateObject * Programs cannot use object pointers in C structures (structs) * Programs cannot use memory zones (NSZone) * To properly cooperate with non-ARC code, programs must use no method or declared property (unless explicitly choosing a different getter) that starts with new.


Property declarations

ARC introduces some new property declaration attributes, some of which replace the old attributes.


Zeroing weak references

Zeroing weak references is a feature in Objective-C ARC that automatically clears (sets to nil) weak-reference local variables, instance variables, and declared properties immediately before the object being pointed to starts deallocating. This ensures that the pointer goes to either a valid object or nil, and avoids
dangling pointer Dangling pointers and wild pointers in computer programming are pointers that do not point to a valid object of the appropriate type. These are special cases of memory safety violations. More generally, dangling references and wild references a ...
s. Prior to the introduction of this feature, "weak references" referred to references that were not retaining, but were not set to nil when the object they pointed to was deallocated (equivalent to unsafe_unretained in ARC), thus possibly leading to a dangling pointer. The programmer typically had to ensure that all possible weak references to an object were set to nil manually when it was being deallocated. Zeroing weak references obviates the need to do this. Zeroing weak references are indicated by using the declared property attribute weak or by using the variable attribute __weak. Zeroing weak references are only available in Mac OS X Lion (10.7) or later and iOS 5 or later, because they require additional support from the Objective-C runtime. However, some OS X classes do not currently support weak references. Code that uses ARC but needs to support versions of the OS older than those above cannot use zeroing weak references, and therefore must use unsafe_unretained weak references. There exists a third-party library called PLWeakCompatibilit

that allows one to use zeroing weak references even on these older OS versions.


Converting to

Xcode Xcode is a suite of developer tools for building apps on Apple devices. It includes an integrated development environment (IDE) of the same name for macOS, used to develop software for macOS, iOS, iPadOS, watchOS, tvOS, and visionOS. It w ...
4.2 or later provides a way to convert code to ARC. As of Xcode 4.5, it is found by choosing Edit > Refactor > Convert to Objective-C ARC... Although Xcode will automatically convert most code, some code may have to be converted manually. Xcode will inform the developer when more complex use cases arise, such as when a variable is declared inside an autorelease pool and used outside it or when two objects need to be toll-free bridged with special casts.


Swift

In Swift, references to objects are strong, unless they are declared weak or unowned. Swift requires explicit handling of nil with the Optional type: a value type that can either have a value or be nil. An Optional type must be handled by "unwrapping" it with a conditional statement, allowing safe usage of the value, if present. Conversely, any non-Optional type will always have a value and cannot be nil. var myString: String // Can only be a string var myOtherString: String? // Can be a string or nil if let myString = myOtherString Accordingly, a strong reference to an object can be of both Optional and non-Optional type (optionality and reference strength are different, albeit related, concepts). A weak reference is always of type Optional, as the object can be deallocated and the reference automatically be set to nil. Unowned references are like weak references but are not set to nil automatically by ARC. They can be either non-Optional or Optional. An unowned reference is expected to always have a value, so accessing the value of an unowned reference after the referenced instance has been deallocated, will result in a runtime error. var strongReference: MyClass // Strong non-Optional reference, cannot be nil var strongOptionalReference: MyClass? // Strong Optional reference, can be nil (manually) weak var weakReference: MyClass? // Weak reference, always Optional, can be nil (automatically or manually) unowned var unownedReference: MyClass // Unowned non-Optional reference, cannot be nil Swift also differs from Objective-C in its usage and encouragement of
value type In certain computer programming languages, data types are classified as either value types or reference types, where reference types are always implicitly accessed via references, whereas value type variables directly contain the values themselves. ...
s instead of
reference type In certain computer programming languages, data types are classified as either value types or reference types, where reference types are always implicitly accessed via references, whereas value type variables directly contain the values themselves. ...
s. Most types in the Swift standard library are value types and they are copied by value, whereas classes and closures are reference types and passed by reference. Because value types are copied when passed around, they are deallocated automatically when the program leaves the scope that contains them.


See also

*
Smart pointer In computer science, a smart pointer is an abstract data type that simulates a pointer while providing added features, such as automatic memory management or bounds checking. Such features are intended to reduce bugs caused by the misuse of p ...


References


External links

* Transitioning to ARC – iOS Developer Library * "Automatic Reference Counting" in ''The Swift Programming Language'' {{Memory management Objective-C Memory management