Automatic Reference Counting

Last updated

Automatic Reference Counting (ARC) is a memory management feature of the Clang compiler providing automatic reference counting for the Objective-C and Swift programming languages. At compile time, it inserts into the object code messages retain and release [1] [2] which increase and decrease the reference count at run time, marking for deallocation those objects when the number of references to them reaches zero.

Contents

ARC differs from tracing garbage collection in that there is no background process that deallocates the objects asynchronously at runtime. [3] Unlike tracing garbage collection, ARC does not handle reference cycles 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 deadlocks and memory leaks. It is up to the developer to break cycles by using weak references. [4]

Apple Inc. deploys ARC in their operating systems, such as macOS (OS X) and iOS. Limited support (ARCLite) [5] has been available since Mac OS X Snow Leopard and iOS 4, with complete support following in Mac OS X Lion and iOS 5. [6] Garbage collection was declared deprecated in OS X Mountain Lion, in favor of ARC, and removed from the Objective-C runtime library in macOS Sierra. [7] [8]

Objective-C

The following rules are enforced by the compiler when ARC is turned on:

Property declarations

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

Without ARCWith ARCWith ARCLite [Note 1]
retainstrong
assign (for object types)weakunsafe_unretained
copy
  1. ARCLite is ARC but without zeroing weak references (used when deploying to a less-capable operating environment than ARC requires).

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 pointers. 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. [9] 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 PLWeakCompatibility that allows one to use zeroing weak references even on these older OS versions.

Converting to

Xcode 4.2 or later provides a way to convert code to ARC. [10] 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.

varmyString:String// Can only be a stringvarmyOtherString:String?// Can be a string or nilifletmyString=myOtherString{// Unwrap the Optionalprint(myString)// Print the string, if present}

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. [11]

varstrongReference:MyClass// Strong non-Optional reference, cannot be nilvarstrongOptionalReference:MyClass?// Strong Optional reference, can be nil (manually)weakvarweakReference:MyClass?// Weak reference, always Optional, can be nil (automatically or manually)unownedvarunownedReference:MyClass// Unowned non-Optional reference, cannot be nil

Swift also differs from Objective-C in its usage and encouragement of value types instead of reference types. 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. [11] [12]

See also

Related Research Articles

<span class="mw-page-title-main">Garbage collection (computer science)</span> Form of automatic memory management

In computer science, garbage collection (GC) is a form of automatic memory management. The garbage collector attempts to reclaim memory which was allocated by the program, but is no longer referenced; such memory is called garbage. Garbage collection was invented by American computer scientist John McCarthy around 1959 to simplify manual memory management in Lisp.

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.

Cocoa is Apple's native object-oriented application programming interface (API) for its desktop operating system macOS.

In programming languages, a closure, also lexical closure or function closure, is a technique for implementing lexically scoped name binding in a language with first-class functions. Operationally, a closure is a record storing a function together with an environment. The environment is a mapping associating each free variable of the function with the value or reference to which the name was bound when the closure was created. Unlike a plain function, a closure allows the function to access those captured variables through the closure's copies of their values or references, even when the function is invoked outside their scope.

<span class="mw-page-title-main">Memory management</span> Computer memory management methodology

Memory management is a form of resource management applied to computer memory. The essential requirement of memory management is to provide ways to dynamically allocate portions of memory to programs at their request, and free it for reuse when no longer needed. This is critical to any advanced computer system where more than a single process might be underway at any time.

In object-oriented (OO) and functional programming, an immutable object is an object whose state cannot be modified after it is created. This is in contrast to a mutable object, which can be modified after it is created. In some cases, an object is considered immutable even if some internally used attributes change, but the object's state appears unchanging from an external point of view. For example, an object that uses memoization to cache the results of expensive computations could still be considered an immutable object.

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 references that reaches the object includes at least one weak reference as a link" – is considered weakly reachable, and can be treated as unreachable and so may be collected at any time. Some garbage-collected languages feature or support various levels of weak references, such as C#, Java, Lisp, OCaml, Perl, Python and PHP since the version 7.4.

In object-oriented programming (OOP), the object lifetime of an object is the time between an object's creation and its destruction. Rules for object lifetime vary significantly between languages, in some cases between implementations of a given language, and lifetime of a particular object may vary from one run of the program to another.

<span class="mw-page-title-main">Xcode</span> IDE including tools for developing software for Apple platforms

Xcode is Apple's integrated development environment (IDE) for macOS, used to develop software for macOS, iOS, iPadOS, watchOS, tvOS, and visionOS. It was initially released in late 2003; the latest stable release is version 15, released on September 18, 2023, and is available free of charge via the Mac App Store and the Apple Developer website. Registered developers can also download preview releases and prior versions of the suite through the Apple Developer website. Xcode includes command-line tools which enable UNIX-style development via the Terminal app in macOS. They can also be downloaded and installed without the GUI.

In computer science, a mutator method is a method used to control changes to a variable. They are also widely known as setter methods. Often a setter is accompanied by a getter, which returns the value of the private member variable. They are also known collectively as accessors.

In computing, a null pointer or null reference is a value saved for indicating that the pointer or reference does not refer to a valid object. Programs routinely use null pointers to represent conditions such as the end of a list of unknown length or the failure to perform some action; this use of null pointers can be compared to nullable types and to the Nothing value in an option type.

Harbour is a computer programming language, primarily used to create database/business programs. It is a modernized, open source and cross-platform version of the older Clipper system, which in turn developed from the dBase database market of the 1980s and 1990s.

In the macOS, iOS, NeXTSTEP, and GNUstep programming frameworks, property list files are files that store serialized objects. Property list files use the filename extension .plist, and thus are often referred to as p-list files.

<span class="mw-page-title-main">Oxygene (programming language)</span> Object Pascal-based programming language

Oxygene is a programming language developed by RemObjects Software for Microsoft's Common Language Infrastructure, the Java Platform and Cocoa. Oxygene is based on Delphi's Object Pascal, but also has influences from C#, Eiffel, Java, F# and other languages.

In object-oriented computer programming, a null object is an object with no referenced value or with defined neutral (null) behavior. The null object design pattern, which describes the uses of such objects and their behavior, was first published as "Void Value" and later in the Pattern Languages of Program Design book series as "Null Object".

The null coalescing operator is a binary operator that is part of the syntax for a basic conditional expression in several programming languages, including C# as of version 2.0, PowerShell as of version 7.0.0, Perl as of version 5.10, Swift, and PHP 7.0.0. While its behavior differs between implementations, the null coalescing operator generally returns the result of its left-most operand if it exists and is not null, and otherwise returns the right-most operand. This behavior allows a default value to be defined for cases where a more specific value is not available.

This article describes the syntax of the C# programming language. The features described are compatible with .NET Framework and Mono.

Objective-C is a high-level general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was selected by NeXT for its NeXTSTEP operating system. Due to Apple macOS’s direct lineage from NeXTSTEP, Objective-C was the standard programming language used, supported, and promoted by Apple for developing macOS and iOS applications until the introduction of the Swift programming language in 2014. Thereafter, its usage has been consistently declining among developers and it has often been described as a "dying" language.

Swift is a high-level general-purpose, multi-paradigm, compiled programming language developed by Apple Inc. and the open-source community. Swift compiles to machine code, as it is an LLVM-based compiler. Swift was first released in June 2014, and the Swift toolchain has shipped in Xcode since version 6, released in 2014.

In object-oriented programming, the safe navigation operator is a binary operator that returns null if its first argument is null; otherwise it performs a dereferencing operation as specified by the second argument.

References

  1. Siracusa, John (July 20, 2011). "Mac OS X 10.7 Lion: the Ars Technica review". Ars Technica . Ars Technica. At section "Automatic Reference Counting". Retrieved November 17, 2016.
  2. Kochan, Stephen G. (2011). Programming in Objective-C (4th ed.). Boston, Mass.: Addison-Wesley. pp.  408. ISBN   978-0321811905.
  3. Hoffman, Kevin (2012). Sams teach yourself Mac OS X Lion app development in 24 hours . Indianapolis, Ind.: Sams. pp.  73. ISBN   9780672335815.
  4. "General". Automatic Reference Counting. LLVM.org. Retrieved 15 August 2012.
  5. "Objective-C Feature Availability Index". Apple, Inc. Retrieved 2013-10-14.
  6. Sakamoto, Kazuki (2012). Pro Multithreading and Memory Management for iOS and OS X with ARC, Grand Central Dispatch and Blocks. Apress. pp. xii. ISBN   978-1430241164.
  7. Siracusa, John (July 25, 2012). "OS X 10.8 Mountain Lion: the Ars Technica review". Ars Technica. At section "Objective-C enhancements". Retrieved November 17, 2016.
  8. "Xcode 8 Release Notes". Apple Developer. October 27, 2016. Archived from the original on March 19, 2017. Retrieved March 19, 2017.
  9. 1 2 3 4 5 6 7 8 "Transitioning to ARC Release Notes" . Retrieved 14 September 2012.
  10. "What's New in Xcode 4.2 – Automatic Reference Counting". Apple Inc. Archived from the original on 20 August 2012. Retrieved 3 October 2012.
  11. 1 2 "Automatic Reference Counting — The Swift Programming Language (Swift 5.7)". docs.swift.org. Retrieved 2022-11-05.
  12. "Value and Reference Types". Apple Developer. August 15, 2014. Retrieved November 17, 2016.