Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Under automatic reference counting, why are retain, release, and dealloc not allowed?

When trying to use -retain, -release, and -dealloc while building my application using automatic reference counting in Xcode 4.2, I get an error like the following:

Automatic Reference Counting forbids explicit message send of 'dealloc'

Why am I seeing this error? Are -retain, -release, and -dealloc no longer allowed under automatic reference counting?

like image 687
Jean Avatar asked Jun 08 '11 01:06

Jean


People also ask

Why is automatic reference counting a type of garbage collection mechanism?

Automatic Reference counting or ARC, is a form of garbage collection in which objects are deallocated once there are no more references to them, i.e. no other variable refers to the object in particular.

What is reference counting in Swift?

Swift uses Automatic Reference Counting (ARC) to track and manage your app's memory usage. In most cases, this means that memory management “just works” in Swift, and you don't need to think about memory management yourself.

What is retain count in Swift?

An essential concept in ARC is the retain count, which is a number that keeps track of how many objects are “holding onto” to another object. ARC only applies to reference types such as classes, and not to value types like structs. Value types are copied, so they don't work with references.

What is OBJC arc?

Automatic Reference Counting (ARC) is a memory management option for Objective-C provided by the Clang compiler. When compiling Objective-C code with ARC enabled, the compiler will effectively retain, release, or autorelease where appropriate to ensure the object's lifetime extends through, at least, its last use.


1 Answers

Basically:

When using ARC, it's all or nothing. Either the compiler is managing all of the retains/releases/deallocs for you, or it is doing nothing. You cannot intersperse your own calls to them, because the compiler wants to do it all itself. It can make absurd optimizations by doing this (for example, a method that returned an autoreleased object under Manual Memory Management may now produce an object that never ends up in an autorelease pool). If you were to start sprinkling in your own calls to retain and release, then the compiler would have to work with these and wouldn't be able to perform a lot of the optimizations that it wants (and that you should want).

And as an added bonus, invoking -retainCount is now a compiler error! OH HAPPY DAY!

like image 159
Dave DeLong Avatar answered Sep 29 '22 13:09

Dave DeLong