ArticleslgStudy

science

Automatic Reference Counting

Automatic Reference Counting is a science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Automatic Reference Counting rather than just read about it. In short: 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 which increase and decrease the reference count at run time, marking for deallocation those objects when the number of references to them reaches zero.

Key takeaways

  • Automatic Reference Counting belongs to science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Automatic Reference Counting to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Automatic Reference Counting from memory before moving on to harder problems.

Reference excerpt

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 which increase and decrease the reference count at run time, marking for deallocation those objects when the number of references to them reaches zero. ARC differs from tracing garbage collection in that there is no background process that deallocates the objects asynchronously at runtime. 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. Apple Inc. deploys ARC in their operating systems, such as macOS (OS X) and iOS. Limited support (ARCLite) has been available since Mac OS X Snow Leopard and iOS 4, with complete support following in Mac OS X Lion and iOS 5. 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.

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 [super dealloc] when dealloc is overridden. 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. 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. 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 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. 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 [1] 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. 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. 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. 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.

See also Smart pointer

References

External links Transitioning to ARC – iOS Developer Library "Automatic Reference Counting" in The Swift Programming Language

Worked examples

Example 1 — a first encounter with Automatic Reference Counting

Start with the simplest possible case. Write down what Automatic Reference Counting claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Automatic Reference Counting before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Automatic Reference Counting ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Automatic Reference Counting

In research
Automatic Reference Counting appears in science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Automatic Reference Counting in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Automatic Reference Counting is common in secondary-school and first-year university syllabi. It links to neighbouring topics Memory management, Objective-C, so understanding it makes those chapters shorter.
In everyday life
Look for Automatic Reference Counting outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Automatic Reference Counting” →

How to study Automatic Reference Counting in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Automatic Reference Counting means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Automatic Reference Counting out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Automatic Reference Counting in simple terms?

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 which increase and decrease the reference…

Why does Automatic Reference Counting matter?

Because it connects several science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Automatic Reference Counting?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Automatic Reference Counting.

Tags

  • Memory management
  • Objective-C

Keep exploring