Objective-C Automatic Reference Counting (ARC)¶
About this document¶
Purpose¶
The first and primary purpose of this document is to serve as a completetechnical specification of Automatic Reference Counting. Given a coreObjective-C compiler and runtime, it should be possible to write a compiler andruntime which implements these new semantics.
The secondary purpose is to act as a rationale for why ARC was designed in thisway. This should remain tightly focused on the technical design and should notstray into marketing speculation.
Background¶
This document assumes a basic familiarity with C.
Blocks are a C language extension for creating anonymous functions.Users interact with and transfer block objects usingblockpointers, which are represented like a normal pointer. A block may capturevalues from local variables; when this occurs, memory must be dynamicallyallocated. The initial allocation is done on the stack, but the runtimeprovides aBlock_copy
function which, given a block pointer, either copiesthe underlying block object to the heap, setting its reference count to 1 andreturning the new block pointer, or (if the block object is already on theheap) increases its reference count by 1. The paired function isBlock_release
, which decreases the reference count by 1 and destroys theobject if the count reaches zero and is on the heap.
Objective-C is a set of language extensions, significant enough to beconsidered a different language. It is a strict superset of C. The extensionscan also be imposed on C++, producing a language called Objective-C++. Theprimary feature is a single-inheritance object system; we briefly describe themodern dialect.
Objective-C defines a new type kind, collectively called theobjectpointer types. This kind has two notable builtin members,id
andClass
;id
is the final supertype of all object pointers. The validityof conversions between object pointer types is not checked at runtime. Usersmay defineclasses; each class is a type, and the pointer to thattype is an object pointer type. A class may have a superclass; its pointertype is a subtype of its superclass’s pointer type. A class has a set ofivars, fields which appear on all instances of that class. Forevery classT there’s an associated metaclass; it has no fields, itssuperclass is the metaclass ofT’s superclass, and its metaclass is a globalclass. Every class has a global object whose class is the class’s metaclass;metaclasses have no associated type, so pointers to this object have typeClass
.
A class declaration (@interface
) declares a set ofmethods. Amethod has a return type, a list of argument types, and aselector:a name likefoo:bar:baz:
, where the number of colons corresponds to thenumber of formal arguments. A method may be an instance method, in which caseit can be invoked on objects of the class, or a class method, in which case itcan be invoked on objects of the metaclass. A method may be invoked byproviding an object (called thereceiver) and a list of formalarguments interspersed with the selector, like so:
[receiverfoo:fooArgbar:barArgbaz:bazArg]
This looks in the dynamic class of the receiver for a method with this name,then in that class’s superclass, etc., until it finds something it can execute.The receiver “expression” may also be the name of a class, in which case theactual receiver is the class object for that class, or (within methoddefinitions) it may besuper
, in which case the lookup algorithm startswith the static superclass instead of the dynamic class. The actual methodsdynamically found in a class are not those declared in the@interface
, butthose defined in a separate@implementation
declaration; however, whencompiling a call, typechecking is done based on the methods declared in the@interface
.
Method declarations may also be grouped intoprotocols, which are notinherently associated with any class, but which classes may claim to follow.Object pointer types may be qualified with additional protocols that the objectis known to support.
Class extensions are collections of ivars and methods, designed toallow a class’s@interface
to be split across multiple files; however,there is still a primary implementation file which must see the@interface
s of all class extensions.Categories allowmethods (but not ivars) to be declaredpost hoc on an arbitrary class; themethods in the category’s@implementation
will be dynamically added to thatclass’s method tables which the category is loaded at runtime, replacing thosemethods in case of a collision.
In the standard environment, objects are allocated on the heap, and theirlifetime is manually managed using a reference count. This is done using twoinstance methods which all classes are expected to implement:retain
increases the object’s reference count by 1, whereasrelease
decreases itby 1 and calls the instance methoddealloc
if the count reaches 0. Tosimplify certain operations, there is also anautorelease pool, athread-local list of objects to callrelease
on later; an object can beadded to this pool by callingautorelease
on it.
Block pointers may be converted to typeid
; block objects are laid out in away that makes them compatible with Objective-C objects. There is a builtinclass that all block objects are considered to be objects of; this classimplementsretain
by adjusting the reference count, not by callingBlock_copy
.
Evolution¶
ARC is under continual evolution, and this document must be updated as thelanguage progresses.
If a change increases the expressiveness of the language, for example bylifting a restriction or by adding new syntax, the change will be annotatedwith a revision marker, like so:
ARC applies to Objective-C pointer types, block pointer types, and[beginning Apple 8.0, LLVM 3.8]BPTRs declaredwithin
extern"BCPL"
blocks.
For now, it is sensible to version this document by the releases of its soleimplementation (and its host project), clang. “LLVM X.Y” refers to anopen-source release of clang from the LLVM project. “Apple X.Y” refers to anApple-provided release of the Apple LLVM Compiler. Other organizations thatprepare their own, separately-versioned clang releases and wish to maintainsimilar information in this document should send requests to cfe-dev.
If a change decreases the expressiveness of the language, for example byimposing a new restriction, this should be taken as an oversight in theoriginal specification and something to be avoided in all versions. Suchchanges are generally to be avoided.
General¶
Automatic Reference Counting implements automatic memory management forObjective-C objects and blocks, freeing the programmer from the need toexplicitly insert retains and releases. It does not provide a cycle collector;users must explicitly manage the lifetime of their objects, breaking cyclesmanually or with weak or unsafe references.
ARC may be explicitly enabled with the compiler flag-fobjc-arc
. It mayalso be explicitly disabled with the compiler flag-fno-objc-arc
. The lastof these two flags appearing on the compile line “wins”.
If ARC is enabled,__has_feature(objc_arc)
will expand to 1 in thepreprocessor. For more information about__has_feature
, see thelanguage extensions document.
Retainable object pointers¶
This section describes retainable object pointers, their basic operations, andthe restrictions imposed on their use under ARC. Note in particular that itcovers the rules for pointervalues (patterns of bits indicating the locationof a pointed-to object), not pointerobjects (locations in memory which storepointer values). The rules for objects are covered in the next section.
Aretainable object pointer (or “retainable pointer”) is a value ofaretainable object pointer type (“retainable type”). There arethree kinds of retainable object pointer types:
block pointers (formed by applying the caret (
^
) declarator sigil to afunction type)Objective-C object pointers (
id
,Class
,NSFoo*
, etc.)typedefs marked with
__attribute__((NSObject))
Other pointer types, such asint*
andCFStringRef
, are not subject toARC’s semantics and restrictions.
Rationale
We are not at liberty to require all code to be recompiled with ARC;therefore, ARC must interoperate with Objective-C code which manages retainsand releases manually. In general, there are three requirements in order fora compiler-supported reference-count system to provide reliableinteroperation:
The type system must reliably identify which objects are to be managed. An
int*
might be a pointer to amalloc
’ed array, or it might be aninterior pointer to such an array, or it might point to some field or localvariable. In contrast, values of the retainable object pointer types arenever interior.The type system must reliably indicate how to manage objects of a type.This usually means that the type must imply a procedure for incrementingand decrementing retain counts. Supporting single-ownership objectsrequires a lot more explicit mediation in the language.
There must be reliable conventions for whether and when “ownership” ispassed between caller and callee, for both arguments and return values.Objective-C methods follow such a convention very reliably, at least forsystem libraries on macOS, and functions always pass objects at +0. TheC-based APIs for Core Foundation objects, on the other hand, have much morevaried transfer semantics.
The use of__attribute__((NSObject))
typedefs is not recommended. If it’sabsolutely necessary to use this attribute, be very explicit about using thetypedef, and do not assume that it will be preserved by language features like__typeof
and C++ template argument substitution.
Rationale
Any compiler operation which incidentally strips type “sugar” from a typewill yield a type without the attribute, which may result in unexpectedbehavior.
Retain count semantics¶
A retainable object pointer is either anull pointer or a pointerto a valid object. Furthermore, if it has block pointer type and is notnull
then it must actually be a pointer to a block object, and if it hasClass
type (possibly protocol-qualified) then it must actually be a pointerto a class object. Otherwise ARC does not enforce the Objective-C type systemas long as the implementing methods follow the signature of the static type.It is undefined behavior if ARC is exposed to an invalid pointer.
For ARC’s purposes, a valid object is one with “well-behaved” retainingoperations. Specifically, the object must be laid out such that theObjective-C message send machinery can successfully send it the followingmessages:
retain
, taking no arguments and returning a pointer to the object.release
, taking no arguments and returningvoid
.autorelease
, taking no arguments and returning a pointer to the object.
The behavior of these methods is constrained in the following ways. The termhigh-level semantics is an intentionally vague term; the intent isthat programmers must implement these methods in a way such that the compiler,modifying code in ways it deems safe according to these constraints, will notviolate their requirements. For example, if the user puts logging statementsinretain
, they should not be surprised if those statements are executedmore or less often depending on optimization settings. These constraints arenot exhaustive of the optimization opportunities: values held in localvariables are subject to additional restrictions, described later in thisdocument.
It is undefined behavior if a computation history featuring a send ofretain
followed by a send ofrelease
to the same object, with nointerveningrelease
on that object, is not equivalent under the high-levelsemantics to a computation history in which these sends are removed. Note thatthis implies that these methods may not raise exceptions.
It is undefined behavior if a computation history features any use whatsoeverof an object following the completion of a send ofrelease
that is notpreceded by a send ofretain
to the same object.
The behavior ofautorelease
must be equivalent to sendingrelease
whenone of the autorelease pools currently in scope is popped. It may not throw anexception.
When the semantics call for performing one of these operations on a retainableobject pointer, if that pointer isnull
then the effect is a no-op.
All of the semantics described in this document are subject to additionaloptimization rules which permit the removal oroptimization of operations based on local knowledge of data flow. Thesemantics describe the high-level behaviors that the compiler implements, notan exact sequence of operations that a program will be compiled into.
Retainable object pointers as operands and arguments¶
In general, ARC does not perform retain or release operations when simply usinga retainable object pointer as an operand within an expression. This includes:
loading a retainable pointer from an object with non-weakownership,
passing a retainable pointer as an argument to a function or method, and
receiving a retainable pointer as the result of a function or method call.
Rationale
While this might seem uncontroversial, it is actually unsafe when multipleexpressions are evaluated in “parallel”, as with binary operators and calls,because (for example) one expression might load from an object while anotherwrites to it. However, C and C++ already call this undefined behaviorbecause the evaluations are unsequenced, and ARC simply exploits that here toavoid needing to retain arguments across a large number of calls.
The remainder of this section describes exceptions to these rules, how thoseexceptions are detected, and what those exceptions imply semantically.
Consumed parameters¶
A function or method parameter of retainable object pointer type may be markedasconsumed, signifying that the callee expects to take ownershipof a +1 retain count. This is done by adding thens_consumed
attribute tothe parameter declaration, like so:
voidfoo(__attribute((ns_consumed))idx);-(void)foo:(id)__attribute((ns_consumed))x;
This attribute is part of the type of the function or method, not the type ofthe parameter. It controls only how the argument is passed and received.
When passing such an argument, ARC retains the argument prior to making thecall.
When receiving such an argument, ARC releases the argument at the end of thefunction, subject to the usual optimizations for local values.
Rationale
This formalizes direct transfers of ownership from a caller to a callee. Themost common scenario here is passing theself
parameter toinit
, butit is useful to generalize. Typically, local optimization will remove anyextra retains and releases: on the caller side the retain will be merged witha +1 source, and on the callee side the release will be rolled into theinitialization of the parameter.
The implicitself
parameter of a method may be marked as consumed by adding__attribute__((ns_consumes_self))
to the method declaration. Methods intheinit
family are treated as if they wereimplicitly marked with this attribute.
It is undefined behavior if an Objective-C message send to a method withns_consumed
parameters (other than self) is made with a null receiver. Itis undefined behavior if the method to which an Objective-C message sendstatically resolves to has a different set ofns_consumed
parameters thanthe method it dynamically resolves to. It is undefined behavior if a block orfunction call is made through a static type with a different set ofns_consumed
parameters than the implementation of the called block orfunction.
Rationale
Consumed parameters with null receiver are a guaranteed leak. Mismatcheswith consumed parameters will cause over-retains or over-releases, dependingon the direction. The rule about function calls is really just anapplication of the existing C/C++ rule about calling functions through anincompatible function type, but it’s useful to state it explicitly.
Retained return values¶
A function or method which returns a retainable object pointer type may bemarked as returning a retained value, signifying that the caller expects to takeownership of a +1 retain count. This is done by adding thens_returns_retained
attribute to the function or method declaration, likeso:
idfoo(void)__attribute((ns_returns_retained));-(id)foo__attribute((ns_returns_retained));
This attribute is part of the type of the function or method.
When returning from such a function or method, ARC retains the value at thepoint of evaluation of the return statement, before leaving all local scopes.
When receiving a return result from such a function or method, ARC releases thevalue at the end of the full-expression it is contained within, subject to theusual optimizations for local values.
Rationale
This formalizes direct transfers of ownership from a callee to a caller. Themost common scenario this models is the retained return frominit
,alloc
,new
, andcopy
methods, but there are other cases in theframeworks. After optimization there are typically no extra retains andreleases required.
Methods in thealloc
,copy
,init
,mutableCopy
, andnew
families are implicitly marked__attribute__((ns_returns_retained))
. This may be suppressed by explicitlymarking the method__attribute__((ns_returns_not_retained))
.
It is undefined behavior if the method to which an Objective-C message sendstatically resolves has different retain semantics on its result from themethod it dynamically resolves to. It is undefined behavior if a block orfunction call is made through a static type with different retain semantics onits result from the implementation of the called block or function.
Rationale
Mismatches with returned results will cause over-retains or over-releases,depending on the direction. Again, the rule about function calls is reallyjust an application of the existing C/C++ rule about calling functionsthrough an incompatible function type.
Unretained return values¶
A method or function which returns a retainable object type but does not returna retained value must ensure that the object is still valid across the returnboundary.
When returning from such a function or method, ARC retains the value at thepoint of evaluation of the return statement, then leaves all local scopes, andthen balances out the retain while ensuring that the value lives across thecall boundary. In the worst case, this may involve anautorelease
, butcallers must not assume that the value is actually in the autorelease pool.
ARC performs no extra mandatory work on the caller side, although it may electto do something to shorten the lifetime of the returned value.
Rationale
It is common in non-ARC code to not return an autoreleased value; thereforethe convention does not force either path. It is convenient to not berequired to do unnecessary retains and autoreleases; this permitsoptimizations such as eliding retain/autoreleases when it can be shown thatthe original pointer will still be valid at the point of return.
A method or function may be marked with__attribute__((ns_returns_autoreleased))
to indicate that it returns apointer which is guaranteed to be valid at least as long as the innermostautorelease pool. There are no additional semantics enforced in the definitionof such a method; it merely enables optimizations in callers.
Bridged casts¶
Abridged cast is a C-style cast annotated with one of threekeywords:
(__bridgeT)op
casts the operand to the destination typeT
. IfT
is a retainable object pointer type, thenop
must have anon-retainable pointer type. IfT
is a non-retainable pointer type,thenop
must have a retainable object pointer type. Otherwise the castis ill-formed. There is no transfer of ownership, and ARC inserts no retainoperations.(__bridge_retainedT)op
casts the operand, which must have retainableobject pointer type, to the destination type, which must be a non-retainablepointer type. ARC retains the value, subject to the usual optimizations onlocal values, and the recipient is responsible for balancing that +1.(__bridge_transferT)op
casts the operand, which must havenon-retainable pointer type, to the destination type, which must be aretainable object pointer type. ARC will release the value at the end ofthe enclosing full-expression, subject to the usual optimizations on localvalues.
These casts are required in order to transfer objects in and out of ARCcontrol; see the rationale in the section onconversion of retainableobject pointers.
Using a__bridge_retained
or__bridge_transfer
cast purely to convinceARC to emit an unbalanced retain or release, respectively, is poor form.
Restrictions¶
Conversion of retainable object pointers¶
In general, a program which attempts to implicitly or explicitly convert avalue of retainable object pointer type to any non-retainable type, orvice-versa, is ill-formed. For example, an Objective-C object pointer shallnot be converted tovoid*
. As an exception, cast tointptr_t
isallowed because such casts are not transferring ownership. Thebridgedcasts may be used to perform these conversionswhere necessary.
Rationale
We cannot ensure the correct management of the lifetime of objects if theymay be freely passed around as unmanaged types. The bridged casts areprovided so that the programmer may explicitly describe whether the casttransfers control into or out of ARC.
However, the following exceptions apply.
Conversion to retainable object pointer type of expressions with known semantics¶
[beginning Apple 4.0, LLVM 3.1]These exceptions have been greatly expanded; they previously appliedonly to a much-reduced subset which is difficult to categorize but whichincluded null pointers, message sends (under the given rules), and the variousglobal constants.
An unbridged conversion to a retainable object pointer type from a type otherthan a retainable object pointer type is ill-formed, as discussed above, unlessthe operand of the cast has a syntactic form which is known retained, knownunretained, or known retain-agnostic.
An expression isknown retain-agnostic if it is:
an Objective-C string literal,
a load from a
const
system global variable ofC retainable pointertype, ora null pointer constant.
An expression isknown unretained if it is an rvalue ofCretainable pointer type and it is:
a direct call to a function, and either that function has the
cf_returns_not_retained
attribute or it is anaudited function that does not have thecf_returns_retained
attribute and does not follow the create/copy namingconvention,a message send, and the declared method either has the
cf_returns_not_retained
attribute or it has neither thecf_returns_retained
attribute nor aselector family that implies a retained result, or[beginning LLVM 3.6]a load from a
const
non-system global variable.
An expression isknown retained if it is an rvalue ofCretainable pointer type and it is:
a message send, and the declared method either has the
cf_returns_retained
attribute, or it does not have thecf_returns_not_retained
attribute but it does have aselectorfamily that implies a retained result.
Furthermore:
a comma expression is classified according to its right-hand side,
a statement expression is classified according to its result expression, ifit has one,
an lvalue-to-rvalue conversion applied to an Objective-C property lvalue isclassified according to the underlying message send, and
a conditional operator is classified according to its second and thirdoperands, if they agree in classification, or else the other if one is knownretain-agnostic.
If the cast operand is known retained, the conversion is treated as a__bridge_transfer
cast. If the cast operand is known unretained or knownretain-agnostic, the conversion is treated as a__bridge
cast.
Rationale
Bridging casts are annoying. Absent the ability to completely automate themanagement of CF objects, however, we are left with relatively poor attemptsto reduce the need for a glut of explicit bridges. Hence these rules.
We’ve so far consciously refrained from implicitly turning retained CFresults from function calls into__bridge_transfer
casts. The worry isthat some code patterns — for example, creating a CF value, assigning itto an ObjC-typed local, and then callingCFRelease
when done — are abit too likely to be accidentally accepted, leading to mysterious behavior.
For loads fromconst
global variables ofC retainable pointer type, it is reasonable to assume that global systemconstants were initialized with true constants (e.g. string literals), butuser constants might have been initialized with something dynamicallyallocated, using a global initializer.
Conversion from retainable object pointer type in certain contexts¶
[beginning Apple 4.0, LLVM 3.1]
If an expression of retainable object pointer type is explicitly cast to aC retainable pointer type, the program isill-formed as discussed above unless the result is immediately used:
to initialize a parameter in an Objective-C message send where the parameteris not marked with the
cf_consumed
attribute, orto initialize a parameter in a direct call to anaudited function where the parameter isnot marked with the
cf_consumed
attribute.
Rationale
Consumed parameters are left out because ARC would naturally balance themwith a retain, which was judged too treacherous. This is in part becauseseveral of the most common consuming functions are in theRelease
family,and it would be quite unfortunate for explicit releases to be silentlybalanced out in this way.
Ownership qualification¶
This section describes the behavior ofobjects of retainable object pointertype; that is, locations in memory which store retainable object pointers.
A type is aretainable object owner type if it is a retainableobject pointer type or an array type whose element type is a retainable objectowner type.
Anownership qualifier is a type qualifier which applies only toretainable object owner types. An array type is ownership-qualified accordingto its element type, and adding an ownership qualifier to an array type soqualifies its element type.
A program is ill-formed if it attempts to apply an ownership qualifier to atype which is already ownership-qualified, even if it is the same qualifier.There is a single exception to this rule: an ownership qualifier may be appliedto a substituted template type parameter, which overrides the ownershipqualifier provided by the template argument.
When forming a function type, the result type is adjusted so that anytop-level ownership qualifier is deleted.
Except as described under theinference rules,a program is ill-formed if it attempts to form a pointer or reference type to aretainable object owner type which lacks an ownership qualifier.
Rationale
These rules, together with the inference rules, ensure that all objects andlvalues of retainable object pointer type have an ownership qualifier. Theability to override an ownership qualifier during template substitution isrequired to counteract theinference of __strong for template typearguments. Ownership qualifierson return types are dropped because they serve no purpose there except tocause spurious problems with overloading and templates.
There are four ownership qualifiers:
__autoreleasing
__strong
__unsafe_unretained
__weak
A type isnontrivially ownership-qualified if it is qualified with__autoreleasing
,__strong
, or__weak
.
Spelling¶
The names of the ownership qualifiers are reserved for the implementation. Aprogram may not assume that they are or are not implemented with macros, orwhat those macros expand to.
An ownership qualifier may be written anywhere that any other type qualifiermay be written.
If an ownership qualifier appears in thedeclaration-specifiers, thefollowing rules apply:
if the type specifier is a retainable object owner type, the qualifierinitially applies to that type;
otherwise, if the outermost non-array declarator is a pointeror block pointer declarator, the qualifier initially applies tothat type;
otherwise the program is ill-formed.
If the qualifier is so applied at a position in the declarationwhere the next-innermost declarator is a function declarator, andthere is an block declarator within that function declarator, thenthe qualifier applies instead to that block declarator and this ruleis considered afresh beginning from the new position.
If an ownership qualifier appears on the declarator name, or on the declaredobject, it is applied to the innermost pointer or block-pointer type.
If an ownership qualifier appears anywhere else in a declarator, it applies tothe type there.
Rationale
Ownership qualifiers are likeconst
andvolatile
in the sensethat they may sensibly apply at multiple distinct positions within adeclarator. However, unlike those qualifiers, there are manysituations where they are not meaningful, and so we make an effortto “move” the qualifier to a place where it will be meaningful. Thegeneral goal is to allow the programmer to write, say,__strong
before the entire declaration and have it apply in the leftmostsensible place.
Property declarations¶
A property of retainable object pointer type may have ownership. If theproperty’s type is ownership-qualified, then the property has that ownership.If the property has one of the following modifiers, then the property has thecorresponding ownership. A property is ill-formed if it has conflictingsources of ownership, or if it has redundant ownership modifiers, or if it has__autoreleasing
ownership.
assign
implies__unsafe_unretained
ownership.copy
implies__strong
ownership, as well as the usual behavior ofcopy semantics on the setter.retain
implies__strong
ownership.strong
implies__strong
ownership.unsafe_unretained
implies__unsafe_unretained
ownership.weak
implies__weak
ownership.
With the exception ofweak
, these modifiers are available in non-ARCmodes.
A property’s specified ownership is preserved in its metadata, but otherwisethe meaning is purely conventional unless the property is synthesized. If aproperty is synthesized, then theassociated instance variable isthe instance variable which is named, possibly implicitly, by the@synthesize
declaration. If the associated instance variable alreadyexists, then its ownership qualification must equal the ownership of theproperty; otherwise, the instance variable is created with that ownershipqualification.
A property of retainable object pointer type which is synthesized without asource of ownership has the ownership of its associated instance variable, if italready exists; otherwise,[beginning Apple 3.1, LLVM 3.1]its ownership is implicitlystrong
. Prior to this revision, itwas ill-formed to synthesize such a property.
Rationale
Usingstrong
by default is safe and consistent with the generic ARC ruleaboutinferring ownership. It is,unfortunately, inconsistent with the non-ARC rule which states that suchproperties are implicitlyassign
. However, that rule is clearlyuntenable in ARC, since it leads to default-unsafe code. The main merit tobanning the properties is to avoid confusion with non-ARC practice, which didnot ultimately strike us as sufficient to justify requiring extra syntax and(more importantly) forcing novices to understand ownership rules just todeclare a property when the default is so reasonable. Changing the rule awayfrom non-ARC practice was acceptable because we had conservatively banned thesynthesis in order to give ourselves exactly this leeway.
Applying__attribute__((NSObject))
to a property not of retainable objectpointer type has the same behavior it does outside of ARC: it requires theproperty type to be some sort of pointer and permits the use of modifiers otherthanassign
. These modifiers only affect the synthesized getter andsetter; direct accesses to the ivar (even if synthesized) still have primitivesemantics, and the value in the ivar will not be automatically released duringdeallocation.
Semantics¶
There are fivemanaged operations which may be performed on anobject of retainable object pointer type. Each qualifier specifies differentsemantics for each of these operations. It is still undefined behavior toaccess an object outside of its lifetime.
A load or store with “primitive semantics” has the same semantics as therespective operation would have on anvoid*
lvalue with the same alignmentand non-ownership qualification.
Reading occurs when performing a lvalue-to-rvalue conversion on anobject lvalue.
For
__weak
objects, the current pointee is retained and then released atthe end of the current full-expression. In particular, messaging a__weak
object keeps the object retained until the end of the full expression.__weakMyObject*weakObj;voidfoo(){// weakObj is retained before the message send and released at the end of// the full expression.[weakObjm];}
This must execute atomically with respect to assignments and to the finalrelease of the pointee.
For all other objects, the lvalue is loaded with primitive semantics.
Assignment occurs when evaluating an assignment operator. Thesemantics vary based on the qualification:
For
__strong
objects, the new pointee is first retained; second, thelvalue is loaded with primitive semantics; third, the new pointee is storedinto the lvalue with primitive semantics; and finally, the old pointee isreleased. This is not performed atomically; external synchronization must beused to make this safe in the face of concurrent loads and stores.For
__weak
objects, the lvalue is updated to point to the new pointee,unless the new pointee is an object currently undergoing deallocation, inwhich case the lvalue is updated to a null pointer. This must executeatomically with respect to other assignments to the object, to reads from theobject, and to the final release of the new pointee.For
__unsafe_unretained
objects, the new pointee is stored into thelvalue using primitive semantics.For
__autoreleasing
objects, the new pointee is retained, autoreleased,and stored into the lvalue using primitive semantics.
Initialization occurs when an object’s lifetime begins, whichdepends on its storage duration. Initialization proceeds in two stages:
First, a null pointer is stored into the lvalue using primitive semantics.This step is skipped if the object is
__unsafe_unretained
.Second, if the object has an initializer, that expression is evaluated andthen assigned into the object using the usual assignment semantics.
Destruction occurs when an object’s lifetime ends. In all cases itis semantically equivalent to assigning a null pointer to the object, with theproviso that of course the object cannot be legally read after the object’slifetime ends.
Moving occurs in specific situations where an lvalue is “movedfrom”, meaning that its current pointee will be used but the object may be leftin a different (but still valid) state. This arises with__block
variablesand rvalue references in C++. For__strong
lvalues, moving is equivalentto loading the lvalue with primitive semantics, writing a null pointer to itwith primitive semantics, and then releasing the result of the load at the endof the current full-expression. For all other lvalues, moving is equivalent toreading the object.
Restrictions¶
Weak-unavailable types¶
It is explicitly permitted for Objective-C classes to not support__weak
references. It is undefined behavior to perform an operation with weakassignment semantics with a pointer to an Objective-C object whose class doesnot support__weak
references.
Rationale
Historically, it has been possible for a class to provide its ownreference-count implementation by overridingretain
,release
, etc.However, weak references to an object require coordination with its class’sreference-count implementation because, among other things, weak loads andstores must be atomic with respect to the final release. Therefore, existingcustom reference-count implementations will generally not support weakreferences without additional effort. This is unavoidable without breakingbinary compatibility.
A class may indicate that it does not support weak references by providing theobjc_arc_weak_reference_unavailable
attribute on the class’s interface declaration. Aretainable object pointer type isweak-unavailable ifis a pointer to an (optionally protocol-qualified) Objective-C classT
whereT
or one of its superclasses has theobjc_arc_weak_reference_unavailable
attribute. A program is ill-formed if it applies the__weak
ownershipqualifier to a weak-unavailable type or if the value operand of a weakassignment operation has a weak-unavailable type.
Storage duration of__autoreleasing
objects¶
A program is ill-formed if it declares an__autoreleasing
object ofnon-automatic storage duration. A program is ill-formed if it captures an__autoreleasing
object in a block or, unless by reference, in a C++11lambda.
Rationale
Autorelease pools are tied to the current thread and scope by their nature.While it is possible to have temporary objects whose instance variables arefilled with autoreleased objects, there is no way that ARC can provide anysort of safety guarantee there.
It is undefined behavior if a non-null pointer is assigned to an__autoreleasing
object while an autorelease pool is in scope and then thatobject is read after the autorelease pool’s scope is left.
Conversion of pointers to ownership-qualified types¶
A program is ill-formed if an expression of typeT*
is converted,explicitly or implicitly, to the typeU*
, whereT
andU
havedifferent ownership qualification, unless:
T
is qualified with__strong
,__autoreleasing
, or__unsafe_unretained
, andU
is qualified with bothconst
and__unsafe_unretained
; oreither
T
orU
iscvvoid
, wherecv
is an optional sequenceof non-ownership qualifiers; orthe conversion is requested with a
reinterpret_cast
in Objective-C++; orthe conversion is a well-formedpass-by-writeback.
The analogous rule applies toT&
andU&
in Objective-C++.
Rationale
These rules provide a reasonable level of type-safety for indirect pointers,as long as the underlying memory is not deallocated. The conversion toconst__unsafe_unretained
is permitted because the semantics of reads areequivalent across all these ownership semantics, and that’s a very useful andcommon pattern. The interconversion withvoid*
is useful for allocatingmemory or otherwise escaping the type system, but use it carefully.reinterpret_cast
is considered to be an obvious enough sign of takingresponsibility for any problems.
It is undefined behavior to access an ownership-qualified object through anlvalue of a differently-qualified type, except that any non-__weak
objectmay be read through an__unsafe_unretained
lvalue.
It is undefined behavior if the storage of a__strong
or__weak
object is not properly initialized before the first managed operationis performed on the object, or if the storage of such an object is freedor reused before the object has been properly deinitialized. Storage fora__strong
or__weak
object may be properly initialized by fillingit with the representation of a null pointer, e.g. by acquiring the memorywithcalloc
or usingbzero
to zero it out. A__strong
or__weak
object may be properly deinitialized by assigning a null pointerinto it. A__strong
object may also be properly initializedby copying into it (e.g. withmemcpy
) the representation of adifferent__strong
object whose storage has been properly initialized;doing this properly deinitializes the source object and causes its storageto no longer be properly initialized. A__weak
object may not berepresentation-copied in this way.
These requirements are followed automatically for objects whoseinitialization and deinitialization are under the control of ARC:
objects of static, automatic, and temporary storage duration
instance variables of Objective-C objects
elements of arrays where the array object’s initialization anddeinitialization are under the control of ARC
fields of Objective-C struct types where the struct object’sinitialization and deinitialization are under the control of ARC
non-static data members of Objective-C++ non-union class types
Objective-C++ objects and arrays of dynamic storage duration createdwith the
new
ornew[]
operators and destroyed with thecorrespondingdelete
ordelete[]
operator
They are not followed automatically for these objects:
objects of dynamic storage duration created in other memory, such asthat returned by
malloc
union members
Rationale
ARC must perform special operations when initializing an object andwhen destroying it. In many common situations, ARC knows when anobject is created and when it is destroyed and can ensure that theseoperations are performed correctly. Otherwise, however, ARC requiresprogrammer cooperation to establish its initialization invariantsbecause it is infeasible for ARC to dynamically infer whether theyare intact. For example, there is no syntactic difference in C betweenan assignment that is intended by the programmer to initialize a variableand one that is intended to replace the existing value stored there,but ARC must perform one operation or the other. ARC chooses to alwaysassume that objects are initialized (except when it is in charge ofinitializing them) because the only workable alternative would be toban all code patterns that could potentially be used to accessuninitialized memory, and that would be too limiting. In practice,this is rarely a problem because programmers do not generally need towork with objects for which the requirements are not handledautomatically.
Note that dynamically-allocated Objective-C++ arrays ofnontrivially-ownership-qualified type are not ABI-compatible with non-ARCcode because the non-ARC code will consider the element type to be POD.Such arrays that arenew[]
’d in ARC translation units cannot bedelete[]
’d in non-ARC translation units and vice-versa.
Passing to an out parameter by writeback¶
If the argument passed to a parameter of typeT__autoreleasing*
has typeUoq*
, whereoq
is an ownership qualifier, then the argument is acandidate forpass-by-writeback` if:
oq
is__strong
or__weak
, andit would be legal to initialize a
T__strong*
with aU__strong*
.
For purposes of overload resolution, an implicit conversion sequence requiringa pass-by-writeback is always worse than an implicit conversion sequence notrequiring a pass-by-writeback.
The pass-by-writeback is ill-formed if the argument expression does not have alegal form:
&var
, wherevar
is a scalar variable of automatic storage durationwith retainable object pointer typea conditional expression where the second and third operands are both legalforms
a cast whose operand is a legal form
a null pointer constant
Rationale
The restriction in the form of the argument serves two purposes. First, itmakes it impossible to pass the address of an array to the argument, whichserves to protect against an otherwise serious risk of mis-inferring an“array” argument as an out-parameter. Second, it makes it much less likelythat the user will see confusing aliasing problems due to the implementation,below, where their store to the writeback temporary is not immediately seenin the original argument variable.
A pass-by-writeback is evaluated as follows:
The argument is evaluated to yield a pointer
p
of typeUoq*
.If
p
is a null pointer, then a null pointer is passed as the argument,and no further work is required for the pass-by-writeback.Otherwise, a temporary of type
T__autoreleasing
is created andinitialized to a null pointer.If the parameter is not an Objective-C method parameter marked
out
,then*p
is read, and the result is written into the temporary withprimitive semantics.The address of the temporary is passed as the argument to the actual call.
After the call completes, the temporary is loaded with primitivesemantics, and that value is assigned into
*p
.
Rationale
This is all admittedly convoluted. In an ideal world, we would see that alocal variable is being passed to an out-parameter and retroactively modifyits type to be__autoreleasing
rather than__strong
. This would beremarkably difficult and not always well-founded under the C type system.However, it was judged unacceptably invasive to require programmers to write__autoreleasing
on all the variables they intend to use forout-parameters. This was the least bad solution.
Ownership-qualified fields of structs and unions¶
A member of a struct or union may be declared to have ownership-qualifiedtype. If the type is qualified with__unsafe_unretained
, the semanticsof the containing aggregate are unchanged from the semantics of an unqualified type in a non-ARC mode. If the type is qualified with__autoreleasing
, the program is ill-formed. Otherwise, if the type is nontrivially ownership-qualified, additional rules apply.
Both Objective-C and Objective-C++ support nontrivially ownership-qualifiedfields. Due to formal differences between the standards, the formaltreatment is different; however, the basic language model is intended tobe the same for identical code.
Rationale
Permitting__strong
and__weak
references in aggregate typesallows programmers to take advantage of the normal language tools ofC and C++ while still automatically managing memory. While it isusually simpler and more idiomatic to use Objective-C objects forsecondary data structures, doing so can introduce extra allocationand message-send overhead, which can cause to unacceptableperformance. Using structs can resolve some of this tension.
__autoreleasing
is forbidden because it is treacherous to relyon autoreleases as an ownership tool outside of a function-localcontexts.
Earlier releases of Clang permitted__strong
and__weak
onlyreferences in Objective-C++ classes, not in Objective-C. Thisrestriction was an undesirable short-term constraint arising from thecomplexity of adding support for non-trivial struct types to C.
In Objective-C++, nontrivially ownership-qualified types are treatedfor nearly all purposes as if they were class types with non-trivialdefault constructors, copy constructors, move constructors, copy assignmentoperators, move assignment operators, and destructors. This includes thedetermination of the triviality of special members of classes with anon-static data member of such a type.
In Objective-C, the definition cannot be so succinct: because the Cstandard lacks rules for non-trivial types, those rules must first bedeveloped. They are given in the next section. The intent is that theserules are largely consistent with the rules of C++ for code expressiblein both languages.
Formal rules for non-trivial types in C¶
The following are base rules which can be added to C to supportimplementation-defined non-trivial types.
A type in C is said to benon-trivial to copy,non-trivial to destroy,ornon-trivial to default-initialize if:
it is a struct or union containing a member whose type is non-trivialto (respectively) copy, destroy, or default-initialize;
it is a qualified type whose unqualified type is non-trivial to(respectively) copy, destroy, or default-initialize (for at leastthe standard C qualifiers); or
it is an array type whose element type is non-trivial to (respectively)copy, destroy, or default-initialize.
A type in C is said to beillegal to copy,illegal to destroy, orillegal to default-initialize if:
it is a union which contains a member whose type is either illegalor non-trivial to (respectively) copy, destroy, or initialize;
it is a qualified type whose unqualified type is illegal to(respectively) copy, destroy, or default-initialize (for at leastthe standard C qualifiers); or
it is an array type whose element type is illegal to (respectively)copy, destroy, or default-initialize.
No type describable under the rules of the C standard shall be eithernon-trivial or illegal to copy, destroy, or default-initialize.An implementation may provide additional types which have one or moreof these properties.
An expression calls for a type to be copied if it:
passes an argument of that type to a function call,
defines a function which declares a parameter of that type,
calls or defines a function which returns a value of that type,
assigns to an l-value of that type, or
converts an l-value of that type to an r-value.
A program calls for a type to be destroyed if it:
passes an argument of that type to a function call,
defines a function which declares a parameter of that type,
calls or defines a function which returns a value of that type,
creates an object of automatic storage duration of that type,
assigns to an l-value of that type, or
converts an l-value of that type to an r-value.
A program calls for a type to be default-initialized if it:
declares a variable of that type without an initializer.
An expression is ill-formed if calls for a type to be copied,destroyed, or default-initialized and that type is illegal to(respectively) copy, destroy, or default-initialize.
A program is ill-formed if it contains a function type specifierwith a parameter or return type that is illegal to copy ordestroy. If a function type specifier would be ill-formed for thisreason except that the parameter or return type was incomplete atthat point in the translation unit, the program is ill-formed butno diagnostic is required.
Agoto
orswitch
is ill-formed if it jumps into the scope ofan object of automatic storage duration whose type is non-trivial todestroy.
C specifies that it is generally undefined behavior to access an l-valueif there is no object of that type at that location. Implementationsare often lenient about this, but non-trivial types generally requireit to be enforced more strictly. The following rules apply:
Thestatic subobjects of a typeT
at a locationL
are:
an object of type
T
spanning fromL
toL+sizeof(T)
;if
T
is a struct type, then for each fieldf
of that struct,the static subobjects ofT
at locationL+offsetof(T,.f)
; andif
T
is the array typeE[N]
, then for eachi
satisfying0<=i<N
, the static subobjects ofE
at locationL+i*sizeof(E)
.
If an l-value is converted to an r-value, then all static subobjectswhose types are non-trivial to copy are accessed. If an l-value isassigned to, or if an object of automatic storage duration goes out ofscope, then all static subobjects of types that are non-trivial to destroyare accessed.
A dynamic object is created at a location if an initialization initializesan object of that type there. A dynamic object ceases to exist at alocation if the memory is repurposed. Memory is repurposed if it isfreed or if a different dynamic object is created there, for example byassigning into a different union member. An implementation may provideadditional rules for what constitutes creating or destroying a dynamicobject.
If an object is accessed under these rules at a location where no suchdynamic object exists, the program has undefined behavior.If memory for a location is repurposed while a dynamic object that isnon-trivial to destroy exists at that location, the program hasundefined behavior.
Rationale
While these rules are far less fine-grained than C++, they arenonetheless sufficient to express a wide spectrum of types.Types that express some sort of ownership will generally be non-trivialto both copy and destroy and either non-trivial or illegal todefault-initialize. Types that don’t express ownership may stillbe non-trivial to copy because of some sort of address sensitivity;for example, a relative reference. Distinguishing defaultinitialization allows types to impose policies about how they arecreated.
These rules assume that assignment into an l-value is always amodification of an existing object rather than an initialization.Assignment is then a compound operation where the old value isread and destroyed, if necessary, and the new value is put intoplace. These are the natural semantics of value propagation, whereall basic operations on the type come down to copies and destroys,and everything else is just an optimization on top of those.
The most glaring weakness of programming with non-trivial types in Cis that there are no language mechanisms (akin to C++’s placementnew
and explicit destructor calls) for explicitly creating anddestroying objects. Clang should consider adding builtins for thispurpose, as well as for common optimizations like destructiverelocation.
Application of the formal C rules to nontrivial ownership qualifiers¶
Nontrivially ownership-qualified types are considered non-trivialto copy, destroy, and default-initialize.
A dynamic object of nontrivially ownership-qualified type contingentlyexists at a location if the memory is filled with a zero pattern, e.g.bycalloc
orbzero
. Such an object can be safely accessed inall of the cases above, but its memory can also be safely repurposed.Assigning a null pointer into an l-value of__weak
or__strong
-qualified type accesses the dynamic object there (and thusmay have undefined behavior if no such object exists), but afterwardsthe object’s memory is guaranteed to be filled with a zero patternand thus may be either further accessed or repurposed as needed.The upshot is that programs may safely initialize dynamically-allocatedmemory for nontrivially ownership-qualified types by ensuring it is zero-initialized, and they may safely deinitialize memory beforefreeing it by storingnil
into any__strong
or__weak
references previously created in that memory.
C/C++ compatibility for structs and unions with non-trivial members¶
Structs and unions with non-trivial members are compatible indifferent language modes (e.g. between Objective-C and Objective-C++,or between ARC and non-ARC modes) under the following conditions:
The types must be compatible ignoring ownership qualifiers accordingto the baseline, non-ARC rules (e.g. C struct compatibility or C++’sODR). This condition implies a pairwise correspondence betweenfields.
Note that an Objective-C++ class with base classes, a user-providedcopy or move constructor, or a user-provided destructor is nevercompatible with an Objective-C type.
If two fields correspond as above, and at least one of the fields isownership-qualified, then:
the fields must be identically qualified, or else
one type must be unqualified (and thus declared in a non-ARC mode),and the other type must be qualified with
__unsafe_unretained
or__strong
.
Note that
__weak
fields must always be declared__weak
becauseof the need to pin those fields in memory and keep them properlyregistered with the Objective-C runtime. Non-ARC modes may stilldeclare fields__weak
by enabling-fobjc-weak
.
These compatibility rules permit a function that takes a parameterof non-trivial struct type to be written in ARC and called fromnon-ARC or vice-versa. The convention for this always transfersownership of objects stored in__strong
fields from the callerto the callee, just as for anns_consumed
argument. Therefore,non-ARC callers must ensure that such fields are initialized to a +1reference, and non-ARC callees must balance that +1 by releasing thereference or transferring it as appropriate.
Likewise, a function returning a non-trivial struct may be written inARC and called from non-ARC or vice-versa. The convention for thisalways transfers ownership of objects stored in__strong
fieldsfrom the callee to the caller, and so callees must initialize suchfields with +1 references, and callers must balance that +1 by releasingor transferring them.
Similar transfers of responsibility occur for__weak
fields, butsince both sides must use native__weak
support to ensurecalling convention compatibility, this transfer is always handledautomatically by the compiler.
Rationale
In earlier releases, when non-trivial ownership was only permittedon fields in Objective-C++, the ABI used for such classes was theordinary ABI for non-trivial C++ classes, which passes arguments andreturns indirectly and does not transfer responsibility for arguments.When support for Objective-C structs was added, it was decided tochange to the current ABI for three reasons:
It permits ARC / non-ARC compatibility for structs containing only
__strong
references, as long as the non-ARC side is careful abouttransferring ownership.It avoids unnecessary indirection for sufficiently small types thatthe C ABI would prefer to pass in registers.
Given that struct arguments must be produced at +1 to satisfy C’ssemantics of initializing the local parameter variable, transferringownership of that copy to the callee is generally better for ARCoptimization, since otherwise there will be releases in the callerthat are much harder to pair with transfers in the callee.
Breaking compatibility with existing Objective-C++ structures wasconsidered an acceptable cost, as most Objective-C++ code does not havebinary-compatibility requirements. Any existing code which cannot acceptthis compatibility break, which is necessarily Objective-C++, shouldforce the use of the standard C++ ABI by declaring an empty (butnon-defaulted) destructor.
Ownership inference¶
Objects¶
If an object is declared with retainable object owner type, but without anexplicit ownership qualifier, its type is implicitly adjusted to have__strong
qualification.
As a special case, if the object’s base type isClass
(possiblyprotocol-qualified), the type is adjusted to have__unsafe_unretained
qualification instead.
Indirect parameters¶
If a function or method parameter has typeT*
, whereT
is anownership-unqualified retainable object pointer type, then:
if
T
isconst
-qualified orClass
, then it is implicitlyqualified with__unsafe_unretained
;otherwise, it is implicitly qualified with
__autoreleasing
.
Rationale
__autoreleasing
exists mostly for this case, the Cocoa convention forout-parameters. Since a pointer toconst
is obviously not anout-parameter, we instead use a type more useful for passing arrays. If theuser instead intends to pass in amutable array, inferring__autoreleasing
is the wrong thing to do; this directs some of thecaution in the following rules about writeback.
Such a type written anywhere else would be ill-formed by the general rulerequiring ownership qualifiers.
This rule does not apply in Objective-C++ if a parameter’s type is dependent ina template pattern and is onlyinstantiated to a type which would be apointer to an unqualified retainable object pointer type. Such code is stillill-formed.
Rationale
The convention is very unlikely to be intentional in template code.
Template arguments¶
If a template argument for a template type parameter is an retainable objectowner type that does not have an explicit ownership qualifier, it is adjustedto have__strong
qualification. This adjustment occurs regardless ofwhether the template argument was deduced or explicitly specified.
Rationale
__strong
is a useful default for containers (e.g.,std::vector<id>
),which would otherwise require explicit qualification. Moreover, unqualifiedretainable object pointer types are unlikely to be useful within templates,since they generally need to have a qualifier applied to the before beingused.
Method families¶
An Objective-C method may fall into amethod family, which is aconventional set of behaviors ascribed to it by the Cocoa conventions.
A method is in a certain method family if:
it has a
objc_method_family
attribute placing it in that family; or ifnot that,it does not have an
objc_method_family
attribute placing it in adifferent or no family, andits selector falls into the corresponding selector family, and
its signature obeys the added restrictions of the method family.
A selector is in a certain selector family if, ignoring any leadingunderscores, the first component of the selector either consists entirely ofthe name of the method family or it begins with that name followed by acharacter other than a lowercase letter. For example,_perform:with:
andperformWith:
would fall into theperform
family (if we recognized one),butperforming:with
would not.
The families and their added restrictions are:
alloc
methods must return a retainable object pointer type.copy
methods must return a retainable object pointer type.mutableCopy
methods must return a retainable object pointer type.new
methods must return a retainable object pointer type.init
methods must be instance methods and must return an Objective-Cpointer type. Additionally, a program is ill-formed if it declares orcontains a call to aninit
method whose return type is neitherid
nora pointer to a super-class or sub-class of the declaring class (if the methodwas declared on a class) or the static receiver type of the call (if it wasdeclared on a protocol).Rationale
There are a fair number of existing methods with
init
-like selectorswhich nonetheless don’t follow theinit
conventions. Typically theseare either accidental naming collisions or helper methods called duringinitialization. Because of the peculiar retain/release behavior ofinit
methods, it’s very important not to treat these methods asinit
methods if they aren’t meant to be. It was felt that implicitlydefining these methods out of the family based on the exact relationshipbetween the return type and the declaring class would be much too subtleand fragile. Therefore we identify a small number of legitimate-seemingreturn types and call everything else an error. This serves the secondarypurpose of encouraging programmers not to accidentally give methods namesin theinit
family.Note that a method with an
init
-family selector which returns anon-Objective-C type (e.g.void
) is perfectly well-formed; it simplyisn’t in theinit
family.
A program is ill-formed if a method’s declarations, implementations, andoverrides do not all have the same method family.
Explicit method family control¶
A method may be annotated with theobjc_method_family
attribute toprecisely control which method family it belongs to. If a method in an@implementation
does not have this attribute, but there is a methoddeclared in the corresponding@interface
that does, then the attribute iscopied to the declaration in the@implementation
. The attribute isavailable outside of ARC, and may be tested for with the preprocessor query__has_attribute(objc_method_family)
.
The attribute is spelled__attribute__((objc_method_family(
family)))
. Iffamily isnone
, the method has no family, even if it would otherwise be considered tohave one based on its selector and type. Otherwise,family must be one ofalloc
,copy
,init
,mutableCopy
, ornew
, in which case themethod is considered to belong to the corresponding family regardless of itsselector. It is an error if a method that is explicitly added to a family inthis way does not meet the requirements of the family other than the selectornaming convention.
Rationale
The rules codified in this document describe the standard conventions ofObjective-C. However, as these conventions have not heretofore been enforcedby an unforgiving mechanical system, they are only imperfectly kept,especially as they haven’t always even been precisely defined. While it ispossible to define low-level ownership semantics with attributes likens_returns_retained
, this attribute allows the user to communicatesemantic intent, which is of use both to ARC (which, e.g., treats calls toinit
specially) and the static analyzer.
Semantics of method families¶
A method’s membership in a method family may imply non-standard semantics forits parameters and return type.
Methods in thealloc
,copy
,mutableCopy
, andnew
families —that is, methods in all the currently-defined families exceptinit
—implicitlyreturn a retained object as if they were annotated withthens_returns_retained
attribute. This can be overridden by annotatingthe method with either of thens_returns_autoreleased
orns_returns_not_retained
attributes.
Properties also follow same naming rules as methods. This means that those inthealloc
,copy
,mutableCopy
, andnew
families provide accesstoretained objects. Thiscan be overridden by annotating the property withns_returns_not_retained
attribute.
Semantics ofinit
¶
Methods in theinit
family implicitlyconsume theirself
parameter andreturn aretained object. Neither ofthese properties can be altered through attributes.
A call to aninit
method with a receiver that is eitherself
(possiblyparenthesized or casted) orsuper
is called adelegate initcall. It is an error for a delegate init call to be made except from aninit
method, and excluding blocks within such methods.
As an exception to theusual rule, the variableself
is mutable in aninit
method and has the usual semantics for a__strong
variable. However, it is undefined behavior and the program is ill-formed, nodiagnostic required, if aninit
method attempts to use the previous valueofself
after the completion of a delegate init call. It is conventional,but not required, for aninit
method to returnself
.
It is undefined behavior for a program to cause two or more calls toinit
methods on the same object, except that eachinit
method invocation mayperform at most one delegate init call.
Related result types¶
Certain methods are candidates to haverelated result types:
class methods in the
alloc
andnew
method familiesinstance methods in the
init
familythe instance method
self
outside of ARC, the instance methods
retain
andautorelease
If the formal result type of such a method isid
or protocol-qualifiedid
, or a type equal to the declaring class or a superclass, then it is saidto have a related result type. In this case, when invoked in an explicitmessage send, it is assumed to return a type related to the type of thereceiver:
if it is a class method, and the receiver is a class name
T
, the messagesend expression has typeT*
; otherwiseif it is an instance method, and the receiver has type
T
, the messagesend expression has typeT
; otherwisethe message send expression has the normal result type of the method.
This is a new rule of the Objective-C language and applies outside of ARC.
Rationale
ARC’s automatic code emission is more prone than most code to signatureerrors, i.e. errors where a call was emitted against one method signature,but the implementing method has an incompatible signature. Having moreprecise type information helps drastically lower this risk, as well ascatching a number of latent bugs.
Optimization¶
Within this section, the wordfunction will be used torefer to any structured unit of code, be it a C function, anObjective-C method, or a block.
This specification describes ARC as performing specificretain
andrelease
operations on retainable object pointers at specificpoints during the execution of a program. These operations make up anon-contiguous subsequence of the computation history of the program.The portion of this sequence for a particular retainable objectpointer for which a specific function execution is directlyresponsible is theformal local retain history of theobject pointer. The corresponding actual sequence executed is thedynamic local retain history.
However, under certain circumstances, ARC is permitted to re-order andeliminate operations in a manner which may alter the overallcomputation history beyond what is permitted by the general “as if”rule of C/C++ and therestrictions onthe implementation ofretain
andrelease
.
Rationale
Specifically, ARC is sometimes permitted to optimizerelease
operations in ways which might cause an object to be deallocatedbefore it would otherwise be. Without this, it would be almostimpossible to eliminate anyretain
/release
pairs. Forexample, consider the following code:
idx=_ivar;[xfoo];
If we were not permitted in any event to shorten the lifetime of theobject inx
, then we would not be able to eliminate this retainand release unless we could prove that the message send could notmodify_ivar
(or deallocateself
). Since message sends areopaque to the optimizer, this is not possible, and so ARC’s handswould be almost completely tied.
ARC makes no guarantees about the execution of a computation historywhich contains undefined behavior. In particular, ARC makes noguarantees in the presence of race conditions.
ARC may assume that any retainable object pointers it receives orgenerates are instantaneously valid from that point until a pointwhich, by the concurrency model of the host language, happens-afterthe generation of the pointer and happens-before a release of thatobject (possibly via an aliasing pointer or indirectly due todestruction of a different object).
Rationale
There is very little point in trying to guarantee correctness in thepresence of race conditions. ARC does not have a stack-scanninggarbage collector, and guaranteeing the atomicity of every load andstore operation would be prohibitive and preclude a vast amount ofoptimization.
ARC may assume that non-ARC code engages in sensible balancingbehavior and does not rely on exact or minimum retain count valuesexcept as guaranteed by__strong
object invariants or +1 transferconventions. For example, if an object is provably double-retainedand double-released, ARC may eliminate the inner retain and release;it does not need to guard against code which performs an unbalancedrelease followed by a “balancing” retain.
Object liveness¶
ARC may not allow a retainable objectX
to be deallocated at atimeT
in a computation history if:
X
is the value stored in a__strong
objectS
withprecise lifetime semantics, orX
is the value stored in a__strong
objectS
withimprecise lifetime semantics and, at some point afterT
butbefore the next store toS
, the computation history features aload fromS
and in some way depends on the value loaded, orX
is a value described as being released at the end of thecurrent full-expression and, at some point afterT
but beforethe end of the full-expression, the computation history dependson that value.
Rationale
The intent of the second rule is to say that objects held in normal__strong
local variables may be released as soon as the value inthe variable is no longer being used: either the variable stopsbeing used completely or a new value is stored in the variable.
The intent of the third rule is to say that return values may bereleased after they’ve been used.
A computation history depends on a pointer valueP
if it:
performs a pointer comparison with
P
,loads from
P
,stores to
P
,depends on a pointer value
Q
derived via pointer arithmeticfromP
(including an instance-variable or field access), ordepends on a pointer value
Q
loaded fromP
.
Dependency applies only to values derived directly or indirectly froma particular expression result and does not occur merely because aseparate pointer value dynamically aliasesP
. Furthermore, thisdependency is not carried by values that are stored to objects.
Rationale
The restrictions on dependency are intended to make this analysisfeasible by an optimizer with only incomplete information about aprogram. Essentially, dependence is carried to “obvious” uses of apointer. Merely passing a pointer argument to a function does notitself cause dependence, but since generally the optimizer will notbe able to prove that the function doesn’t depend on that parameter,it will be forced to conservatively assume it does.
Dependency propagates to values loaded from a pointer because thosevalues might be invalidated by deallocating the object. Forexample, given the code__strongidx=p->ivar;
, ARC must notmove the release ofp
to between the load ofp->ivar
and theretain of that value for storing intox
.
Dependency does not propagate through stores of dependent pointervalues because doing so would allow dependency to outlive thefull-expression which produced the original value. For example, theaddress of an instance variable could be written to some globallocation and then freely accessed during the lifetime of the local,or a function could return an inner pointer of an object and storeit to a local. These cases would be potentially impossible toreason about and so would basically prevent any optimizations basedon imprecise lifetime. There are also uncommon enough to make itreasonable to require the precise-lifetime annotation if someonereally wants to rely on them.
Dependency does propagate through return values of pointer type.The compelling source of need for this rule is a property accessorwhich returns an un-autoreleased result; the calling function musthave the chance to operate on the value, e.g. to retain it, beforeARC releases the original pointer. Note again, however, thatdependence does not survive a store, so ARC does not guarantee thecontinued validity of the return value past the end of thefull-expression.
No object lifetime extension¶
If, in the formal computation history of the program, an objectX
has been deallocated by the time of an observable side-effect, thenARC must causeX
to be deallocated by no later than the occurrenceof that side-effect, except as influenced by the re-ordering of thedestruction of objects.
Rationale
This rule is intended to prohibit ARC from observably extending thelifetime of a retainable object, other than as specified in thisdocument. Together with the rule limiting the transformation ofreleases, this rule requires ARC to eliminate retains and releaseonly in pairs.
ARC’s power to reorder the destruction of objects is critical to itsability to do any optimization, for essentially the same reason thatit must retain the power to decrease the lifetime of an object.Unfortunately, while it’s generally poor style for the destructionof objects to have arbitrary side-effects, it’s certainly possible.Hence the caveat.
Precise lifetime semantics¶
In general, ARC maintains an invariant that a retainable object pointer held ina__strong
object will be retained for the full formal lifetime of theobject. Objects subject to this invariant haveprecise lifetimesemantics.
By default, local variables of automatic storage duration do not have preciselifetime semantics. Such objects are simply strong references which holdvalues of retainable object pointer type, and these values are still fullysubject to the optimizations on values under local control.
Rationale
Applying these precise-lifetime semantics strictly would be prohibitive.Many useful optimizations that might theoretically decrease the lifetime ofan object would be rendered impossible. Essentially, it promises too much.
A local variable of retainable object owner type and automatic storage durationmay be annotated with theobjc_precise_lifetime
attribute to indicate thatit should be considered to be an object with precise lifetime semantics.
Rationale
Nonetheless, it is sometimes useful to be able to force an object to bereleased at a precise time, even if that object does not appear to be used.This is likely to be uncommon enough that the syntactic weight of explicitlyrequesting these semantics will not be burdensome, and may even make the codeclearer.
Miscellaneous¶
Special methods¶
Memory management methods¶
A program is ill-formed if it contains a method definition, message send, or@selector
expression for any of the following selectors:
autorelease
release
retain
retainCount
Rationale
retainCount
is banned because ARC robs it of consistent semantics. Theothers were banned after weighing three options for how to deal with messagesends:
Honoring them would work out very poorly if a programmer naively oraccidentally tried to incorporate code written for manual retain/release codeinto an ARC program. At best, such code would do twice as much work asnecessary; quite frequently, however, ARC and the explicit code would bothtry to balance the same retain, leading to crashes. The cost is losing theability to perform “unrooted” retains, i.e. retains not logicallycorresponding to a strong reference in the object graph.
Ignoring them would badly violate user expectations about their code.While itwould make it easier to develop code simultaneously for ARC andnon-ARC, there is very little reason to do so except for certain librarydevelopers. ARC and non-ARC translation units share an execution model andcan seamlessly interoperate. Within a translation unit, a developer whofaithfully maintains their code in non-ARC mode is suffering all therestrictions of ARC for zero benefit, while a developer who isn’t testing thenon-ARC mode is likely to be unpleasantly surprised if they try to go back toit.
Banning them has the disadvantage of making it very awkward to migrateexisting code to ARC. The best answer to that, given a number of otherchanges and restrictions in ARC, is to provide a specialized tool to assistusers in that migration.
Implementing these methods was banned because they are too integral to thesemantics of ARC; many tricks which worked tolerably under manual referencecounting will misbehave if ARC performs an ephemeral extra retain or two. Ifabsolutely required, it is still possible to implement them in non-ARC code,for example in a category; the implementations must obey thesemantics laid out elsewhere in this document.
dealloc
¶
A program is ill-formed if it contains a message send or@selector
expression for the selectordealloc
.
Rationale
There are no legitimate reasons to calldealloc
directly.
A class may provide a method definition for an instance method nameddealloc
. This method will be called after the finalrelease
of theobject but before it is deallocated or any of its instance variables aredestroyed. The superclass’s implementation ofdealloc
will be calledautomatically when the method returns.
Rationale
Even though ARC destroys instance variables automatically, there are stilllegitimate reasons to write adealloc
method, such as freeingnon-retainable resources. Failing to call[superdealloc]
in such amethod is nearly always a bug. Sometimes, the object is simply trying toprevent itself from being destroyed, butdealloc
is really far too latefor the object to be raising such objections. Somewhat more legitimately, anobject may have been pool-allocated and should not be deallocated withfree
; for now, this can only be supported with adealloc
implementation outside of ARC. Such an implementation must be very carefulto do all the other work thatNSObject
’sdealloc
would, which isoutside the scope of this document to describe.
The instance variables for an ARC-compiled class will be destroyed at somepoint after control enters thedealloc
method for the root class of theclass. The ordering of the destruction of instance variables is unspecified,both within a single class and between subclasses and superclasses.
Rationale
The traditional, non-ARC pattern for destroying instance variables is todestroy them immediately before calling[superdealloc]
. Unfortunately,message sends from the superclass are quite capable of reaching methods inthe subclass, and those methods may well read or write to those instancevariables. Making such message sends from dealloc is generally discouraged,since the subclass may well rely on other invariants that were broken duringdealloc
, but it’s not so inescapably dangerous that we felt comfortablecalling it undefined behavior. Therefore we chose to delay destroying theinstance variables to a point at which message sends are clearly disallowed:the point at which the root class’s deallocation routines take over.
In most code, the difference is not observable. It can, however, be observedif an instance variable holds a strong reference to an object whosedeallocation will trigger a side-effect which must be carefully ordered withrespect to the destruction of the super class. Such code violates the designprinciple that semantically important behavior should be explicit. A simplefix is to clear the instance variable manually duringdealloc
; a moreholistic solution is to move semantically important side-effects out ofdealloc
and into a separate teardown phase which can rely on working withwell-formed objects.
@autoreleasepool
¶
To simplify the use of autorelease pools, and to bring them under the controlof the compiler, a new kind of statement is available in Objective-C. It iswritten@autoreleasepool
followed by acompound-statement, i.e. by a newscope delimited by curly braces. Upon entry to this block, the current stateof the autorelease pool is captured. When the block is exited normally,whether by fallthrough or directed control flow (such asreturn
orbreak
), the autorelease pool is restored to the saved state, releasing allthe objects in it. When the block is exited with an exception, the pool is notdrained.
@autoreleasepool
may be used in non-ARC translation units, with equivalentsemantics.
A program is ill-formed if it refers to theNSAutoreleasePool
class.
Rationale
Autorelease pools are clearly important for the compiler to reason about, butit is far too much to expect the compiler to accurately reason about controldependencies between two calls. It is also very easy to accidentally forgetto drain an autorelease pool when using the manual API, and this cansignificantly inflate the process’s high-water-mark. The introduction of anew scope is unfortunate but basically required for sane interaction with therest of the language. Not draining the pool during an unwind is apparentlyrequired by the Objective-C exceptions implementation.
Externally-Retained Variables¶
In some situations, variables with strong ownership are consideredexternally-retained by the implementation. This means that the variable isretained elsewhere, and therefore the implementation can elide retaining andreleasing its value. Such a variable is implicitlyconst
for safety. Incontrast with__unsafe_unretained
, an externally-retained variable stillbehaves as a strong variable outside of initialization and destruction. Forinstance, when an externally-retained variable is captured in a block the valueof the variable is retained and released on block capture and destruction. Italso affects C++ features such as lambda capture,decltype
, and templateargument deduction.
Implicitly, the implementation assumes that theself parameter in anon-init method and thevariable in a for-in loop are externally-retained.
Externally-retained semantics can also be opted into with theobjc_externally_retained
attribute. This attribute can apply to strong localvariables, functions, methods, or blocks:
@classWobbleAmount;@interfaceWidget :NSObject-(void)wobble:(WobbleAmount*)amount;@end@implementationWidget-(void)wobble:(WobbleAmount*)amount__attribute__((objc_externally_retained)){// 'amount' and 'alias' aren't retained on entry, nor released on exit.__attribute__((objc_externally_retained))WobbleAmount*alias=amount;}@end
Annotating a function with this attribute makes every parameter with strongretainable object pointer type externally-retained, unless the variable wasexplicitly qualified with__strong
. For instance,first_param
isexternally-retained (and thereforeconst
) below, but notsecond_param
:
__attribute__((objc_externally_retained))voidf(NSArray*first_param,__strongNSArray*second_param){// ...}
You can test if your compiler has support forobjc_externally_retained
with__has_attribute
:
#if __has_attribute(objc_externally_retained)// Use externally retained...#endif
self
¶
Theself
parameter variable of an non-init Objective-C method is consideredexternally-retained by the implementation.It is undefined behavior, or at least dangerous, to cause an object to bedeallocated during a message send to that object. In an init method,self
follows the :ref:initfamilyrules<arc.family.semantics.init>
.
Rationale
The cost of retainingself
in all methods was found to be prohibitive, asit tends to be live across calls, preventing the optimizer from proving thatthe retain and release are unnecessary — for good reason, as it’s quitepossible in theory to cause an object to be deallocated during its executionwithout this retain and release. Since it’s extremely uncommon to actuallydo so, even unintentionally, and since there’s no natural way for theprogrammer to remove this retain/release pair otherwise (as there is forother parameters by, say, making the variableobjc_externally_retained
orqualifying it with__unsafe_unretained
), we chose to make this optimizingassumption and shift some amount of risk to the user.
Fast enumeration iteration variables¶
If a variable is declared in the condition of an Objective-C fast enumerationloop, and the variable has no explicit ownership qualifier, then it isimplicitlyexternally-retained so thatobjects encountered during the enumeration are not actually retained andreleased.
Rationale
This is an optimization made possible because fast enumeration loops promiseto keep the objects retained during enumeration, and the collection itselfcannot be synchronously modified. It can be overridden by explicitlyqualifying the variable with__strong
, which will make the variablemutable again and cause the loop to retain the objects it encounters.
Blocks¶
The implicitconst
capture variables created when evaluating a blockliteral expression have the same ownership semantics as the local variablesthey capture. The capture is performed by reading from the captured variableand initializing the capture variable with that value; the capture variable isdestroyed when the block literal is, i.e. at the end of the enclosing scope.
Theinference rules apply equally to__block
variables, which is a shift in semantics from non-ARC, where__block
variables did not implicitly retain during capture.
__block
variables of retainable object owner type are moved off the stackby initializing the heap copy with the result of moving from the stack copy.
With the exception of retains done as part of initializing a__strong
parameter variable or reading a__weak
variable, whenever these semanticscall for retaining a value of block-pointer type, it has the effect of aBlock_copy
. The optimizer may remove such copies when it sees that theresult is used only as an argument to a call.
When a block pointer type is converted to a non-block pointer type (such asid
),Block_copy
is called. This is necessary because a block allocatedon the stack won’t get copied to the heap when the non-block pointer escapes.A block pointer is implicitly converted toid
when it is passed to afunction as a variadic argument.
Exceptions¶
By default in Objective C, ARC is not exception-safe for normal releases:
It does not end the lifetime of
__strong
variables when their scopes areabnormally terminated by an exception.It does not perform releases which would occur at the end of afull-expression if that full-expression throws an exception.
A program may be compiled with the option-fobjc-arc-exceptions
in order toenable these, or with the option-fno-objc-arc-exceptions
to explicitlydisable them, with the last such argument “winning”.
Rationale
The standard Cocoa convention is that exceptions signal programmer error andare not intended to be recovered from. Making code exceptions-safe bydefault would impose severe runtime and code size penalties on code thattypically does not actually care about exceptions safety. Therefore,ARC-generated code leaks by default on exceptions, which is just fine if theprocess is going to be immediately terminated anyway. Programs which do careabout recovering from exceptions should enable the option.
In Objective-C++,-fobjc-arc-exceptions
is enabled by default.
Rationale
C++ already introduces pervasive exceptions-cleanup code of the sort that ARCintroduces. C++ programmers who have not already disabled exceptions aremuch more likely to actual require exception-safety.
ARC does end the lifetimes of__weak
objects when an exception terminatestheir scope unless exceptions are disabled in the compiler.
Rationale
The consequence of a local__weak
object not being destroyed is verylikely to be corruption of the Objective-C runtime, so we want to be saferhere. Of course, potentially massive leaks are about as likely to take downthe process as this corruption is if the program does try to recover fromexceptions.
Interior pointers¶
An Objective-C method returning a non-retainable pointer may be annotated withtheobjc_returns_inner_pointer
attribute to indicate that it returns ahandle to the internal data of an object, and that this reference will beinvalidated if the object is destroyed. When such a message is sent to anobject, the object’s lifetime will be extended until at least the earliest of:
the last use of the returned pointer, or any pointer derived from it, in thecalling function or
the autorelease pool is restored to a previous state.
Rationale
Rationale: not all memory and resources are managed with reference counts; itis common for objects to manage private resources in their own, private way.Typically these resources are completely encapsulated within the object, butsome classes offer their users direct access for efficiency. If ARC is notaware of methods that return such “interior” pointers, its optimizations cancause the owning object to be reclaimed too soon. This attribute informs ARCthat it must tread lightly.
The extension rules are somewhat intentionally vague. The autorelease poollimit is there to permit a simple implementation to simply retain andautorelease the receiver. The other limit permits some amount ofoptimization. The phrase “derived from” is intended to encompass the resultsboth of pointer transformations, such as casts and arithmetic, and of loadingfrom such derived pointers; furthermore, it applies whether or not suchderivations are applied directly in the calling code or by other utility code(for example, the C library routinestrchr
). However, the implementationnever need account for uses after a return from the code which calls themethod returning an interior pointer.
As an exception, no extension is required if the receiver is loaded directlyfrom a__strong
object withprecise lifetime semantics.
Rationale
Implicit autoreleases carry the risk of significantly inflating memory use,so it’s important to provide users a way of avoiding these autoreleases.Tying this to precise lifetime semantics is ideal, as for local variablesthis requires a very explicit annotation, which allows ARC to trust the userwith good cheer.
C retainable pointer types¶
A type is aC retainable pointer type if it is a pointer to(possibly qualified)void
or a pointer to a (possibly qualifier)struct
orclass
type.
Rationale
ARC does not manage pointers of CoreFoundation type (or any of the relatedfamilies of retainable C pointers which interoperate with Objective-C forretain/release operation). In fact, ARC does not even know how todistinguish these types from arbitrary C pointer types. The intent of thisconcept is to filter out some obviously non-object types while leaving a hookfor later tightening if a means of exhaustively marking CF types is madeavailable.
Auditing of C retainable pointer interfaces¶
[beginning Apple 4.0, LLVM 3.1]
A C function may be marked with thecf_audited_transfer
attribute toexpress that, except as otherwise marked with attributes, it obeys theparameter (consuming vs. non-consuming) and return (retained vs. non-retained)conventions for a C function of its name, namely:
A parameter of C retainable pointer type is assumed to not be consumedunless it is marked with the
cf_consumed
attribute, andA result of C retainable pointer type is assumed to not be returned retainedunless the function is either marked
cf_returns_retained
or it followsthe create/copy naming convention and is not markedcf_returns_not_retained
.
A function obeys thecreate/copy naming convention if its namecontains as a substring:
either “Create” or “Copy” not followed by a lowercase letter, or
either “create” or “copy” not followed by a lowercase letter andnot preceded by any letter, whether uppercase or lowercase.
A second attribute,cf_unknown_transfer
, signifies that a function’stransfer semantics cannot be accurately captured using any of theseannotations. A program is ill-formed if it annotates the same function withbothcf_audited_transfer
andcf_unknown_transfer
.
A pragma is provided to facilitate the mass annotation of interfaces:
#pragma clang arc_cf_code_audited begin...#pragma clang arc_cf_code_audited end
All C functions declared within the extent of this pragma are treated as ifannotated with thecf_audited_transfer
attribute unless they otherwise havethecf_unknown_transfer
attribute. The pragma is accepted in all languagemodes. A program is ill-formed if it attempts to change files, whether byincluding a file or ending the current file, within the extent of this pragma.
It is possible to test for all the features in this section with__has_feature(arc_cf_code_audited)
.
Rationale
A significant inconvenience in ARC programming is the necessity ofinteracting with APIs based around C retainable pointers. These features aredesigned to make it relatively easy for API authors to quickly review andannotate their interfaces, in turn improving the fidelity of tools such asthe static analyzer and ARC. The single-file restriction on the pragma isdesigned to eliminate the risk of accidentally annotating some other header’sinterfaces.
Runtime support¶
This section describes the interaction between the ARC runtime and the codegenerated by the ARC compiler. This is not part of the ARC languagespecification; instead, it is effectively a language-specific ABI supplement,akin to the “Itanium” generic ABI for C++.
Ownership qualification does not alter the storage requirements for objects,except that it is undefined behavior if a__weak
object is inadequatelyaligned for an object of typeid
. The other qualifiers may be used onexplicitly under-aligned memory.
The runtime tracks__weak
objects which holds non-null values. It isundefined behavior to direct modify a__weak
object which is being trackedby the runtime except through anobjc_storeWeak,objc_destroyWeak, orobjc_moveWeak call.
The runtime must provide a number of new entrypoints which the compiler mayemit, which are described in the remainder of this section.
Rationale
Several of these functions are semantically equivalent to a message send; weemit calls to C functions instead because:
the machine code to do so is significantly smaller,
it is much easier to recognize the C functions in the ARC optimizer, and
a sufficient sophisticated runtime may be able to avoid the message send incommon cases.
Several other of these functions are “fused” operations which can bedescribed entirely in terms of other operations. We use the fused operationsprimarily as a code-size optimization, although in some cases there is also areal potential for avoiding redundant operations in the runtime.
idobjc_autorelease(idvalue);
¶
Precondition:value
is null or a pointer to a valid object.
Ifvalue
is null, this call has no effect. Otherwise, it adds the objectto the innermost autorelease pool exactly as if the object had been sent theautorelease
message.
Always returnsvalue
.
voidobjc_autoreleasePoolPop(void*pool);
¶
Precondition:pool
is the result of a previous call toobjc_autoreleasePoolPush on thecurrent thread, where neitherpool
nor any enclosing pool have previouslybeen popped.
Releases all the objects added to the given autorelease pool and anyautorelease pools it encloses, then sets the current autorelease pool to thepool directly enclosingpool
.
void*objc_autoreleasePoolPush(void);
¶
Creates a new autorelease pool that is enclosed by the current pool, makes thatthe current pool, and returns an opaque “handle” to it.
Rationale
While the interface is described as an explicit hierarchy of pools, the rulesallow the implementation to just keep a stack of objects, using the stackdepth as the opaque pool handle.
idobjc_autoreleaseReturnValue(idvalue);
¶
Precondition:value
is null or a pointer to a valid object.
Ifvalue
is null, this call has no effect. Otherwise, it makes a besteffort to hand off ownership of a retain count on the object to a call toobjc_retainAutoreleasedReturnValue (orobjc_unsafeClaimAutoreleasedReturnValue) for the same object inan enclosing call frame. If this is not possible, the object is autoreleased asabove.
Always returnsvalue
.
voidobjc_copyWeak(id*dest,id*src);
¶
Precondition:src
is a valid pointer which either contains a null pointeror has been registered as a__weak
object.dest
is a valid pointerwhich has not been registered as a__weak
object.
dest
is initialized to be equivalent tosrc
, potentially registering itwith the runtime. Equivalent to the following code:
voidobjc_copyWeak(id*dest,id*src){objc_release(objc_initWeak(dest,objc_loadWeakRetained(src)));}
Must be atomic with respect to calls toobjc_storeWeak
onsrc
.
voidobjc_destroyWeak(id*object);
¶
Precondition:object
is a valid pointer which either contains a nullpointer or has been registered as a__weak
object.
object
is unregistered as a weak object, if it ever was. The current valueofobject
is left unspecified; otherwise, equivalent to the following code:
voidobjc_destroyWeak(id*object){objc_storeWeak(object,nil);}
Does not need to be atomic with respect to calls toobjc_storeWeak
onobject
.
idobjc_initWeak(id*object,idvalue);
¶
Precondition:object
is a valid pointer which has not been registered asa__weak
object.value
is null or a pointer to a valid object.
Ifvalue
is a null pointer or the object to which it points has begundeallocation,object
is zero-initialized. Otherwise,object
isregistered as a__weak
object pointing tovalue
. Equivalent to thefollowing code:
idobjc_initWeak(id*object,idvalue){*object=nil;returnobjc_storeWeak(object,value);}
Returns the value ofobject
after the call.
Does not need to be atomic with respect to calls toobjc_storeWeak
onobject
.
idobjc_loadWeak(id*object);
¶
Precondition:object
is a valid pointer which either contains a nullpointer or has been registered as a__weak
object.
Ifobject
is registered as a__weak
object, and the last value storedintoobject
has not yet been deallocated or begun deallocation, retains andautoreleases that value and returns it. Otherwise returns null. Equivalent tothe following code:
idobjc_loadWeak(id*object){returnobjc_autorelease(objc_loadWeakRetained(object));}
Must be atomic with respect to calls toobjc_storeWeak
onobject
.
Rationale
Loading weak references would be inherently prone to race conditions withoutthe retain.
idobjc_loadWeakRetained(id*object);
¶
Precondition:object
is a valid pointer which either contains a nullpointer or has been registered as a__weak
object.
Ifobject
is registered as a__weak
object, and the last value storedintoobject
has not yet been deallocated or begun deallocation, retainsthat value and returns it. Otherwise returns null.
Must be atomic with respect to calls toobjc_storeWeak
onobject
.
voidobjc_moveWeak(id*dest,id*src);
¶
Precondition:src
is a valid pointer which either contains a null pointeror has been registered as a__weak
object.dest
is a valid pointerwhich has not been registered as a__weak
object.
dest
is initialized to be equivalent tosrc
, potentially registering itwith the runtime.src
may then be left in its original state, in whichcase this call is equivalent toobjc_copyWeak, or it may be left as null.
Must be atomic with respect to calls toobjc_storeWeak
onsrc
.
voidobjc_release(idvalue);
¶
Precondition:value
is null or a pointer to a valid object.
Ifvalue
is null, this call has no effect. Otherwise, it performs arelease operation exactly as if the object had been sent therelease
message.
idobjc_retain(idvalue);
¶
Precondition:value
is null or a pointer to a valid object.
Ifvalue
is null, this call has no effect. Otherwise, it performs a retainoperation exactly as if the object had been sent theretain
message.
Always returnsvalue
.
idobjc_retainAutorelease(idvalue);
¶
Precondition:value
is null or a pointer to a valid object.
Ifvalue
is null, this call has no effect. Otherwise, it performs a retainoperation followed by an autorelease operation. Equivalent to the followingcode:
idobjc_retainAutorelease(idvalue){returnobjc_autorelease(objc_retain(value));}
Always returnsvalue
.
idobjc_retainAutoreleaseReturnValue(idvalue);
¶
Precondition:value
is null or a pointer to a valid object.
Ifvalue
is null, this call has no effect. Otherwise, it performs a retainoperation followed by the operation described inobjc_autoreleaseReturnValue.Equivalent to the following code:
idobjc_retainAutoreleaseReturnValue(idvalue){returnobjc_autoreleaseReturnValue(objc_retain(value));}
Always returnsvalue
.
idobjc_retainAutoreleasedReturnValue(idvalue);
¶
Precondition:value
is null or a pointer to a valid object.
Ifvalue
is null, this call has no effect. Otherwise, it attempts toaccept a hand off of a retain count from a call toobjc_autoreleaseReturnValue onvalue
in a recently-called function or something it tail-calls. If thatfails, it performs a retain operation exactly likeobjc_retain.
Always returnsvalue
.
idobjc_retainBlock(idvalue);
¶
Precondition:value
is null or a pointer to a valid block object.
Ifvalue
is null, this call has no effect. Otherwise, if the block pointedto byvalue
is still on the stack, it is copied to the heap and the addressof the copy is returned. Otherwise a retain operation is performed on theblock exactly as if it had been sent theretain
message.
voidobjc_storeStrong(id*object,idvalue);
¶
Precondition:object
is a valid pointer to a__strong
object which isadequately aligned for a pointer.value
is null or a pointer to a validobject.
Performs the complete sequence for assigning to a__strong
object ofnon-block type[*]. Equivalent to the following code:
voidobjc_storeStrong(id*object,idvalue){idoldValue=*object;value=[valueretain];*object=value;[oldValuerelease];}
This does not imply that a__strong
object of block type is aninvalid argument to this function. Rather it implies that anobjc_retain
and not anobjc_retainBlock
operation will be emitted if the argument isa block.
idobjc_storeWeak(id*object,idvalue);
¶
Precondition:object
is a valid pointer which either contains a nullpointer or has been registered as a__weak
object.value
is null or apointer to a valid object.
Ifvalue
is a null pointer or the object to which it points has begundeallocation,object
is assigned null and unregistered as a__weak
object. Otherwise,object
is registered as a__weak
object or has itsregistration updated to point tovalue
.
Returns the value ofobject
after the call.
idobjc_unsafeClaimAutoreleasedReturnValue(idvalue);
¶
Precondition:value
is null or a pointer to a valid object.
Ifvalue
is null, this call has no effect. Otherwise, it attempts toaccept a hand off of a retain count from a call toobjc_autoreleaseReturnValue onvalue
in a recently-called function or something it tail-calls (in a mannersimilar toobjc_retainAutoreleasedReturnValue). If that succeeds,it performs a release operation exactly likeobjc_release. If the handoff fails, this call has no effect.
Always returnsvalue
.