blob: 244f9e6a1fc0a446fd664495690809ec53d11298 [file] [log] [blame]
John McCall82467022011-06-15 21:21:53 +00001<html>
2<head>
3<title>Objective-C Automatic Reference Counting (ARC)</title>
4<link type="text/css" rel="stylesheet" href="../menu.css" />
5<link type="text/css" rel="stylesheet" href="../content.css" />
6<style type="text/css">
7/* Collapse the items in the ToC to the left. */
8div#toc ul {
9 padding-left: 0
10}
11
12/* Rationales appear in italic. */
13div.rationale {
14 font-style: italic
15}
16
John McCallf3d08a62011-06-18 07:31:30 +000017div.rationale em {
18 font-style: normal
19}
20
John McCall82467022011-06-15 21:21:53 +000021div h1 { font-size: 2em; margin: .67em 0 }
22div div h1 { font-size: 1.5em; margin: .75em 0 }
23div div div h1 { font-size: 1.17em; margin: .83em 0 }
24div div div div h1 { margin: 1.12em 0 }
25
26span.term { font-style: italic; font-weight: bold }
27</style>
28
29<script lang="javascript">
30/// A little script to recursively build a table of contents.
31function buildTOC(div, toc, ancestry) {
32 var children = div.childNodes;
33 var len = children.length;
34
35 var childNumber = 0;
36
37 var list = null;
38 for (var i = 0; i < len; ++i) {
39 var child = children[i];
40 if (child.nodeName != "DIV") continue;
41 if (child.getAttribute("class") == "rationale") continue;
42 if (child.id == "toc") continue;
43
44 // Okay, we're actually going to build a list node.
45 if (list === null) list = document.createElement("ul");
46
47 var childAncestry = ancestry + ++childNumber + ".";
48
49 var headerNode = child.childNodes[1];
50 var title = headerNode.innerHTML;
51 headerNode.insertBefore(document.createTextNode(childAncestry + " "),
52 headerNode.firstChild);
53
54 var item = document.createElement("li");
55 item.appendChild(document.createTextNode(childAncestry + " "));
56
57 var anchor = document.createElement("a");
58 anchor.href = "#" + child.id;
59 anchor.innerHTML = title;
60 item.appendChild(anchor);
61
62 buildTOC(child, item, childAncestry);
63
64 list.appendChild(item);
65 }
66 if (list) toc.appendChild(list);
67}
68
69function onLoad() {
70 var toc = document.getElementById("toc");
71 var content = document.getElementById("content");
72 buildTOC(content, toc, "");
73}
74window.onload = onLoad;
75
76</script>
77</head>
78<body>
79
80<!--#include virtual="../menu.html.incl"-->
81
82<div id="content">
83<h1>Automatic Reference Counting</h1>
84
85<div id="toc">
86</div>
87
88<div id="meta">
89<h1>About this document</h1>
90
91<div id="meta.purpose">
92<h1>Purpose</h1>
93
94<p>The first and primary purpose of this document is to serve as a
95complete technical specification of Automatic Reference Counting.
96Given a core Objective-C compiler and runtime, it should be possible
97to write a compiler and runtime which implements these new
98semantics.</p>
99
100<p>The secondary purpose is to act as a rationale for why ARC was
101designed in this way. This should remain tightly focused on the
102technical design and should not stray into marketing speculation.</p>
103
104</div> <!-- meta.purpose -->
105
106<div id="meta.background">
107<h1>Background</h1>
108
109<p>This document assumes a basic familiarity with C.</p>
110
111<p><span class="term">Blocks</span> are a C language extension for
112creating anonymous functions. Users interact with and transfer block
113objects using <span class="term">block pointers</span>, which are
114represented like a normal pointer. A block may capture values from
115local variables; when this occurs, memory must be dynamically
116allocated. The initial allocation is done on the stack, but the
117runtime provides a <tt>Block_copy</tt> function which, given a block
118pointer, either copies the underlying block object to the heap,
119setting its reference count to 1 and returning the new block pointer,
120or (if the block object is already on the heap) increases its
121reference count by 1. The paired function is <tt>Block_release</tt>,
122which decreases the reference count by 1 and destroys the object if
123the count reaches zero and is on the heap.</p>
124
125<p>Objective-C is a set of language extensions, significant enough to
126be considered a different language. It is a strict superset of C.
127The extensions can also be imposed on C++, producing a language called
128Objective-C++. The primary feature is a single-inheritance object
129system; we briefly describe the modern dialect.</p>
130
131<p>Objective-C defines a new type kind, collectively called
132the <span class="term">object pointer types</span>. This kind has two
133notable builtin members, <tt>id</tt> and <tt>Class</tt>; <tt>id</tt>
134is the final supertype of all object pointers. The validity of
135conversions between object pointer types is not checked at runtime.
136Users may define <span class="term">classes</span>; each class is a
137type, and the pointer to that type is an object pointer type. A class
138may have a superclass; its pointer type is a subtype of its
139superclass's pointer type. A class has a set
140of <span class="term">ivars</span>, fields which appear on all
141instances of that class. For every class <i>T</i> there's an
142associated metaclass; it has no fields, its superclass is the
143metaclass of <i>T</i>'s superclass, and its metaclass is a global
144class. Every class has a global object whose class is the
145class's metaclass; metaclasses have no associated type, so pointers to
146this object have type <tt>Class</tt>.</p>
147
148<p>A class declaration (<tt>@interface</tt>) declares a set
149of <span class="term">methods</span>. A method has a return type, a
150list of argument types, and a <span class="term">selector</span>: a
151name like <tt>foo:bar:baz:</tt>, where the number of colons
152corresponds to the number of formal arguments. A method may be an
153instance method, in which case it can be invoked on objects of the
154class, or a class method, in which case it can be invoked on objects
155of the metaclass. A method may be invoked by providing an object
156(called the <span class="term">receiver</span>) and a list of formal
157arguments interspersed with the selector, like so:</p>
158
159<pre>[receiver foo: fooArg bar: barArg baz: bazArg]</pre>
160
161<p>This looks in the dynamic class of the receiver for a method with
162this name, then in that class's superclass, etc., until it finds
163something it can execute. The receiver <q>expression</q> may also be
164the name of a class, in which case the actual receiver is the class
165object for that class, or (within method definitions) it may
166be <tt>super</tt>, in which case the lookup algorithm starts with the
167static superclass instead of the dynamic class. The actual methods
168dynamically found in a class are not those declared in the
169<tt>@interface</tt>, but those defined in a separate
170<tt>@implementation</tt> declaration; however, when compiling a
171call, typechecking is done based on the methods declared in the
172<tt>@interface</tt>.</p>
173
174<p>Method declarations may also be grouped into
175<span class="term">protocols</span>, which are not inherently
176associated with any class, but which classes may claim to follow.
177Object pointer types may be qualified with additional protocols that
178the object is known to support.</p>
179
180<p><span class="term">Class extensions</span> are collections of ivars
181and methods, designed to allow a class's <tt>@interface</tt> to be
182split across multiple files; however, there is still a primary
183implementation file which must see the <tt>@interface</tt>s of all
184class extensions.
185<span class="term">Categories</span> allow methods (but not ivars) to
186be declared <i>post hoc</i> on an arbitrary class; the methods in the
187category's <tt>@implementation</tt> will be dynamically added to that
188class's method tables which the category is loaded at runtime,
189replacing those methods in case of a collision.</p>
190
191<p>In the standard environment, objects are allocated on the heap, and
192their lifetime is manually managed using a reference count. This is
193done using two instance methods which all classes are expected to
194implement: <tt>retain</tt> increases the object's reference count by
1951, whereas <tt>release</tt> decreases it by 1 and calls the instance
196method <tt>dealloc</tt> if the count reaches 0. To simplify certain
197operations, there is also an <span class="term">autorelease
198pool</span>, a thread-local list of objects to call <tt>release</tt>
199on later; an object can be added to this pool by
200calling <tt>autorelease</tt> on it.</p>
201
202<p>Block pointers may be converted to type <tt>id</tt>; block objects
203are laid out in a way that makes them compatible with Objective-C
204objects. There is a builtin class that all block objects are
205considered to be objects of; this class implements <tt>retain</tt> by
206adjusting the reference count, not by calling <tt>Block_copy</tt>.</p>
207
208</div> <!-- meta.background -->
209
210</div> <!-- meta -->
211
212<div id="general">
213<h1>General</h1>
214
215<p>Automatic Reference Counting implements automatic memory management
216for Objective-C objects and blocks, freeing the programmer from the
217need explicitly insert retains and releases. It does not provide a
218cycle collector; users must explicitly manage lifetime instead.</p>
219
220<p>ARC may be explicitly enabled with the compiler
221flag <tt>-fobjc-arc</tt>. It may also be explicitly disabled with the
222compiler flag <tt>-fno-objc-arc</tt>. The last of these two flags
223appearing on the compile line <q>wins</q>.</p>
224
225<p>If ARC is enabled, <tt>__has_feature(objc_arc)</tt> will expand to
2261 in the preprocessor. For more information about <tt>__has_feature</tt>,
227see the <a href="LanguageExtensions.html#__has_feature_extension">language
228extensions</a> document.</p>
229
230</div>
231
232<div id="objects">
233<h1>Retainable object pointers</h1>
234
235<p>This section describes retainable object pointers, their basic
236operations, and the restrictions imposed on their use under ARC. Note
237in particular that it covers the rules for pointer <em>values</em>
238(patterns of bits indicating the location of a pointed-to object), not
239pointer
240<em>objects</em> (locations in memory which store pointer values).
241The rules for objects are covered in the next section.</p>
242
243<p>A <span class="term">retainable object pointer</span>
244(or <q>retainable pointer</q>) is a value of
245a <span class="term">retainable object pointer type</span>
246(<q>retainable type</q>). There are three kinds of retainable object
247pointer types:</p>
248<ul>
249<li>block pointers (formed by applying the caret (<tt>^</tt>)
250declarator sigil to a function type)</li>
251<li>Objective-C object pointers (<tt>id</tt>, <tt>Class</tt>, <tt>NSFoo*</tt>, etc.)</li>
252<li>typedefs marked with <tt>__attribute__((NSObject))</tt></li>
253</ul>
254
255<p>Other pointer types, such as <tt>int*</tt> and <tt>CFStringRef</tt>,
256are not subject to ARC's semantics and restrictions.</p>
257
258<div class="rationale">
259
260<p>Rationale: We are not at liberty to require
261all code to be recompiled with ARC; therefore, ARC must interoperate
262with Objective-C code which manages retains and releases manually. In
263general, there are three requirements in order for a
264compiler-supported reference-count system to provide reliable
265interoperation:</p>
266
267<ul>
268<li>The type system must reliably identify which objects are to be
269managed. An <tt>int*</tt> might be a pointer to a <tt>malloc</tt>'ed
270array, or it might be a interior pointer to such an array, or it might
271point to some field or local variable. In contrast, values of the
272retainable object pointer types are never interior.</li>
273<li>The type system must reliably indicate how to
274manage objects of a type. This usually means that the type must imply
275a procedure for incrementing and decrementing retain counts.
276Supporting single-ownership objects requires a lot more explicit
277mediation in the language.</li>
278<li>There must be reliable conventions for whether and
279when <q>ownership</q> is passed between caller and callee, for both
280arguments and return values. Objective-C methods follow such a
281convention very reliably, at least for system libraries on Mac OS X,
282and functions always pass objects at +0. The C-based APIs for Core
283Foundation objects, on the other hand, have much more varied transfer
284semantics.</li>
285</ul>
286</div> <!-- rationale -->
287
288<p>The use of <tt>__attribute__((NSObject))</tt> typedefs is not
289recommended. If it's absolutely necessary to use this attribute, be
290very explicit about using the typedef, and do not assume that it will
291be preserved by language features like <tt>__typeof</tt> and C++
292template argument substitution.</p>
293
294<div class="rationale"><p>Rationale: any compiler operation which
295incidentally strips type <q>sugar</q> from a type will yield a type
296without the attribute, which may result in unexpected
297behavior.</p></div>
298
299<div id="objects.retains">
300<h1>Retain count semantics</h1>
301
302<p>A retainable object pointer is either a <span class="term">null
303pointer</span> or a pointer to a valid object. Furthermore, if it has
304block pointer type and is not <tt>null</tt> then it must actually be a
305pointer to a block object, and if it has <tt>Class</tt> type (possibly
306protocol-qualified) then it must actually be a pointer to a class
307object. Otherwise ARC does not enforce the Objective-C type system as
308long as the implementing methods follow the signature of the static
309type. It is undefined behavior if ARC is exposed to an invalid
310pointer.</p>
311
312<p>For ARC's purposes, a valid object is one with <q>well-behaved</q>
313retaining operations. Specifically, the object must be laid out such
314that the Objective-C message send machinery can successfully send it
315the following messages:</p>
316
317<ul>
318<li><tt>retain</tt>, taking no arguments and returning a pointer to
319the object.</li>
320<li><tt>release</tt>, taking no arguments and returning <tt>void</tt>.</li>
321<li><tt>autorelease</tt>, taking no arguments and returning a pointer
322to the object.</li>
323</ul>
324
325<p>The behavior of these methods is constrained in the following ways.
326The term <span class="term">high-level semantics</span> is an
327intentionally vague term; the intent is that programmers must
328implement these methods in a way such that the compiler, modifying
329code in ways it deems safe according to these constraints, will not
330violate their requirements. For example, if the user puts logging
331statements in <tt>retain</tt>, they should not be surprised if those
332statements are executed more or less often depending on optimization
333settings. These constraints are not exhaustive of the optimization
334opportunities: values held in local variables are subject to
335additional restrictions, described later in this document.</p>
336
337<p>It is undefined behavior if a computation history featuring a send
338of <tt>retain</tt> followed by a send of <tt>release</tt> to the same
339object, with no intervening <tt>release</tt> on that object, is not
340equivalent under the high-level semantics to a computation
341history in which these sends are removed. Note that this implies that
342these methods may not raise exceptions.</p>
343
344<p>It is undefined behavior if a computation history features any use
345whatsoever of an object following the completion of a send
346of <tt>release</tt> that is not preceded by a send of <tt>retain</tt>
347to the same object.</p>
348
349<p>The behavior of <tt>autorelease</tt> must be equivalent to sending
350<tt>release</tt> when one of the autorelease pools currently in scope
351is popped. It may not throw an exception.</p>
352
353<p>When the semantics call for performing one of these operations on a
354retainable object pointer, if that pointer is <tt>null</tt> then the
355effect is a no-op.</p>
356
357<p>All of the semantics described in this document are subject to
358additional <a href="#optimization">optimization rules</a> which permit
359the removal or optimization of operations based on local knowledge of
360data flow. The semantics describe the high-level behaviors that the
361compiler implements, not an exact sequence of operations that a
362program will be compiled into.</p>
363
364</div> <!-- objects.retains -->
365
366<div id="objects.operands">
367<h1>Retainable object pointers as operands and arguments</h1>
368
369<p>In general, ARC does not perform retain or release operations when
370simply using a retainable object pointer as an operand within an
371expression. This includes:</p>
372<ul>
373<li>loading a retainable pointer from an object with non-weak
374<a href="#ownership">ownership</a>,</li>
375<li>passing a retainable pointer as an argument to a function or
376method, and</li>
377<li>receiving a retainable pointer as the result of a function or
378method call.</li>
379</ul>
380
381<div class="rationale"><p>Rationale: while this might seem
382uncontroversial, it is actually unsafe when multiple expressions are
383evaluated in <q>parallel</q>, as with binary operators and calls,
384because (for example) one expression might load from an object while
385another writes to it. However, C and C++ already call this undefined
386behavior because the evaluations are unsequenced, and ARC simply
387exploits that here to avoid needing to retain arguments across a large
388number of calls.</p></div>
389
390<p>The remainder of this section describes exceptions to these rules,
391how those exceptions are detected, and what those exceptions imply
392semantically.</p>
393
394<div id="objects.operands.consumed">
395<h1>Consumed parameters</h1>
396
397<p>A function or method parameter of retainable object pointer type
398may be marked as <span class="term">consumed</span>, signifying that
399the callee expects to take ownership of a +1 retain count. This is
400done by adding the <tt>ns_consumed</tt> attribute to the parameter
401declaration, like so:</p>
402
403<pre>void foo(__attribute((ns_consumed)) id x);
404- (void) foo: (id) __attribute((ns_consumed)) x;</pre>
405
406<p>This attribute is part of the type of the function or method, not
407the type of the parameter. It controls only how the argument is
408passed and received.</p>
409
410<p>When passing such an argument, ARC retains the argument prior to
411making the call.</p>
412
413<p>When receiving such an argument, ARC releases the argument at the
414end of the function, subject to the usual optimizations for local
415values.</p>
416
417<div class="rationale"><p>Rationale: this formalizes direct transfers
418of ownership from a caller to a callee. The most common scenario here
419is passing the <tt>self</tt> parameter to <tt>init</tt>, but it is
420useful to generalize. Typically, local optimization will remove any
421extra retains and releases: on the caller side the retain will be
422merged with a +1 source, and on the callee side the release will be
423rolled into the initialization of the parameter.</p></div>
424
425<p>The implicit <tt>self</tt> parameter of a method may be marked as
426consumed by adding <tt>__attribute__((ns_consumes_self))</tt> to the
John McCallbe16b892011-06-18 08:15:19 +0000427method declaration. Methods in the <tt>init</tt>
428<a href="#family">family</a> are treated as if they were implicitly
429marked with this attribute.</p>
John McCall82467022011-06-15 21:21:53 +0000430
John McCallbe16b892011-06-18 08:15:19 +0000431<p>It is undefined behavior if an Objective-C message send to a method
432with <tt>ns_consumed</tt> parameters (other than self) is made with a
433null receiver. It is undefined behavior if the method to which an
434Objective-C message send statically resolves to has a different set
435of <tt>ns_consumed</tt> parameters than the method it dynamically
436resolves to. It is undefined behavior if a block or function call is
437made through a static type with a different set of <tt>ns_consumed</tt>
438parameters than the implementation of the called block or function.</p>
John McCall82467022011-06-15 21:21:53 +0000439
John McCallbe16b892011-06-18 08:15:19 +0000440<div class="rationale"><p>Rationale: consumed parameters with null
441receiver are a guaranteed leak. Mismatches with consumed parameters
442will cause over-retains or over-releases, depending on the direction.
443The rule about function calls is really just an application of the
444existing C/C++ rule about calling functions through an incompatible
445function type, but it's useful to state it explicitly.</p></div>
John McCall82467022011-06-15 21:21:53 +0000446
447</div>
448
John McCallbe16b892011-06-18 08:15:19 +0000449<div id="objects.operands.retained_returns">
John McCall82467022011-06-15 21:21:53 +0000450<h1>Retained return values</h1>
451
452<p>A function or method which returns a retainable object pointer type
453may be marked as returning a retained value, signifying that the
454caller expects to take ownership of a +1 retain count. This is done
455by adding the <tt>ns_returns_retained</tt> attribute to the function or
456method declaration, like so:</p>
457
458<pre>id foo(void) __attribute((ns_returns_retained));
459- (id) foo __attribute((ns_returns_retained));</pre>
460
461<p>This attribute is part of the type of the function or method.</p>
462
463<p>When returning from such a function or method, ARC retains the
464value at the point of evaluation of the return statement, before
465leaving all local scopes.</p>
466
467<p>When receiving a return result from such a function or method, ARC
468releases the value at the end of the full-expression it is contained
469within, subject to the usual optimizations for local values.</p>
470
471<div class="rationale"><p>Rationale: this formalizes direct transfers of
472ownership from a callee to a caller. The most common scenario this
473models is the retained return from <tt>init</tt>, <tt>alloc</tt>,
474<tt>new</tt>, and <tt>copy</tt> methods, but there are other cases in
475the frameworks. After optimization there are typically no extra
476retains and releases required.</p></div>
477
478<p>Methods in
479the <tt>alloc</tt>, <tt>copy</tt>, <tt>init</tt>, <tt>mutableCopy</tt>,
480and <tt>new</tt> <a href="#family">families</a> are implicitly marked
481<tt>__attribute__((ns_returns_retained))</tt>. This may be suppressed
482by explicitly marking the
483method <tt>__attribute__((ns_returns_not_retained))</tt>.</p>
484</div>
485
John McCallbe16b892011-06-18 08:15:19 +0000486<p>It is undefined behavior if the method to which an Objective-C
487message send statically resolves has different retain semantics on its
488result from the method it dynamically resolves to. It is undefined
489behavior if a block or function call is made through a static type
490with different retain semantics on its result from the implementation
491of the called block or function.</p>
492
493<div class="rationale"><p>Rationale: Mismatches with returned results
494will cause over-retains or over-releases, depending on the direction.
495Again, the rule about function calls is really just an application of
496the existing C/C++ rule about calling functions through an
497incompatible function type.</p></div>
498
499
John McCall82467022011-06-15 21:21:53 +0000500<div id="objects.operands.other-returns">
501<h1>Unretained return values</h1>
502
503<p>A method or function which returns a retainable object type but
504does not return a retained value must ensure that the object is
505still valid across the return boundary.</p>
506
507<p>When returning from such a function or method, ARC retains the
508value at the point of evaluation of the return statement, then leaves
509all local scopes, and then balances out the retain while ensuring that
510the value lives across the call boundary. In the worst case, this may
511involve an <tt>autorelease</tt>, but callers must not assume that the
512value is actually in the autorelease pool.</p>
513
514<p>ARC performs no extra mandatory work on the caller side, although
515it may elect to do something to shorten the lifetime of the returned
516value.</p>
517
518<div class="rationale"><p>Rationale: it is common in non-ARC code to not
519return an autoreleased value; therefore the convention does not force
520either path. It is convenient to not be required to do unnecessary
521retains and autoreleases; this permits optimizations such as eliding
522retain/autoreleases when it can be shown that the original pointer
523will still be valid at the point of return.</p></div>
524
525<p>A method or function may be marked
526with <tt>__attribute__((ns_returns_autoreleased))</tt> to indicate
527that it returns a pointer which is guaranteed to be valid at least as
528long as the innermost autorelease pool. There are no additional
529semantics enforced in the definition of such a method; it merely
530enables optimizations in callers.</p>
531</div>
532
533<div id="objects.operands.casts">
534<h1>Bridged casts</h1>
535
536<p>A <span class="term">bridged cast</span> is a C-style cast
537annotated with one of three keywords:</p>
538
539<ul>
540<li><tt>(__bridge T) op</tt> casts the operand to the destination
541type <tt>T</tt>. If <tt>T</tt> is a retainable object pointer type,
542then <tt>op</tt> must have a non-retainable pointer type.
543If <tt>T</tt> is a non-retainable pointer type, then <tt>op</tt> must
544have a retainable object pointer type. Otherwise the cast is
545ill-formed. There is no transfer of ownership, and ARC inserts
546no retain operations.</li>
547
548<li><tt>(__bridge_retained T) op</tt> casts the operand, which must
549have retainable object pointer type, to the destination type, which
550must be a non-retainable pointer type. ARC retains the value, subject
551to the usual optimizations on local values, and the recipient is
552responsible for balancing that +1.</li>
553
554<li><tt>(__bridge_transfer T) op</tt> casts the operand, which must
555have non-retainable pointer type, to the destination type, which must
556be a retainable object pointer type. ARC will release the value at
557the end of the enclosing full-expression, subject to the usual
558optimizations on local values.</li>
559</ul>
560
561<p>These casts are required in order to transfer objects in and out of
562ARC control; see the rationale in the section
563on <a href="#objects.restrictions.conversion">conversion of retainable
564object pointers</a>.</p>
565
566<p>Using a <tt>__bridge_retained</tt> or <tt>__bridge_transfer</tt>
567cast purely to convince ARC to emit an unbalanced retain or release,
568respectively, is poor form.</p>
569
570</div>
571
572</div>
573
574<div id="objects.restrictions">
575<h1>Restrictions</h1>
576
577<div id="objects.restrictions.conversion">
578<h1>Conversion of retainable object pointers</h1>
579
580<p>In general, a program which attempts to implicitly or explicitly
581convert a value of retainable object pointer type to any
582non-retainable type, or vice-versa, is ill-formed. For example, an
Fariborz Jahaniana26b2e52011-07-06 21:58:44 +0000583Objective-C object pointer shall not be converted to <tt>void*</tt>.
584As an exception, cast to <tt>intptr_t</tt> is allowed becuase such
585casts are not transferring ownership. The <a href="#objects.operands.casts">bridged
John McCall82467022011-06-15 21:21:53 +0000586casts</a> may be used to perform these conversions where
587necessary.</p>
588
589<div class="rationale"><p>Rationale: we cannot ensure the correct
590management of the lifetime of objects if they may be freely passed
591around as unmanaged types. The bridged casts are provided so that the
592programmer may explicitly describe whether the cast transfers control
593into or out of ARC.</p></div>
594</div>
595
596<p>An unbridged cast to a retainable object pointer type of the return
597value of a Objective-C message send which yields a non-retainable
598pointer is treated as a <tt>__bridge_transfer</tt> cast
599if:</p>
600
601<ul>
602<li>the method has the <tt>cf_returns_retained</tt> attribute, or if
603not that,</li>
604<li>the method does not have the <tt>cf_returns_not_retained</tt>
605attribute and</li>
606<li>the method's <a href="#family">selector family</a> would imply
607the <tt>ns_returns_retained</tt> attribute on a method which returned
608a retainable object pointer type.</li>
609</ul>
610
611<p>Otherwise the cast is treated as a <tt>__bridge</tt> cast.</p>
612
613</div>
614
615</div>
616
617<div id="ownership">
618<h1>Ownership qualification</h1>
619
620<p>This section describes the behavior of <em>objects</em> of
621retainable object pointer type; that is, locations in memory which
622store retainable object pointers.</p>
623
624<p>A type is a <span class="term">retainable object owner type</span>
625if it is a retainable object pointer type or an array type whose
626element type is a retainable object owner type.</p>
627
628<p>An <span class="term">ownership qualifier</span> is a type
Douglas Gregor4020cae2011-06-17 23:16:24 +0000629qualifier which applies only to retainable object owner types. An array type is
630ownership-qualified according to its element type, and adding an ownership
631qualifier to an array type so qualifies its element type.</p>
632
633<p>A program is ill-formed if it attempts to apply an ownership qualifier
John McCall82467022011-06-15 21:21:53 +0000634to a type which is already ownership-qualified, even if it is the same
Douglas Gregor4020cae2011-06-17 23:16:24 +0000635qualifier. There is a single exception to this rule: an ownership qualifier
636may be applied to a substituted template type parameter, which overrides the
637ownership qualifier provided by the template argument.</p>
John McCall82467022011-06-15 21:21:53 +0000638
639<p>Except as described under
640the <a href="#ownership.inference">inference rules</a>, a program is
641ill-formed if it attempts to form a pointer or reference type to a
642retainable object owner type which lacks an ownership qualifier.</p>
643
644<div class="rationale"><p>Rationale: these rules, together with the
645inference rules, ensure that all objects and lvalues of retainable
Douglas Gregor4020cae2011-06-17 23:16:24 +0000646object pointer type have an ownership qualifier. The ability to override an ownership qualifier during template substitution is required to counteract the <a href="#ownership.inference.template_arguments">inference of <tt>__strong</tt> for template type arguments</a>. </p></div>
John McCall82467022011-06-15 21:21:53 +0000647
648<p>There are four ownership qualifiers:</p>
649
650<ul>
651<li><tt>__autoreleasing</tt></li>
652<li><tt>__strong</tt></li>
653<li><tt>__unsafe_unretained</tt></li>
654<li><tt>__weak</tt></li>
655</ul>
656
657<p>A type is <span class="term">nontrivially ownership-qualified</span>
658if it is qualified with <tt>__autoreleasing</tt>, <tt>__strong</tt>, or
659<tt>__weak</tt>.</p>
660
661<div id="ownership.spelling">
662<h1>Spelling</h1>
663
664<p>The names of the ownership qualifiers are reserved for the
665implementation. A program may not assume that they are or are not
666implemented with macros, or what those macros expand to.</p>
667
668<p>An ownership qualifier may be written anywhere that any other type
669qualifier may be written.</p>
670
671<p>If an ownership qualifier appears in
672the <i>declaration-specifiers</i>, the following rules apply:</p>
673
674<ul>
675<li>if the type specifier is a retainable object owner type, the
676qualifier applies to that type;</li>
677<li>if the outermost non-array part of the declarator is a pointer or
678block pointer, the qualifier applies to that type;</li>
679<li>otherwise the program is ill-formed.</li>
680</ul>
681
682<p>If an ownership qualifier appears on the declarator name, or on the
683declared object, it is applied to outermost pointer or block-pointer
684type.</p>
685
686<p>If an ownership qualifier appears anywhere else in a declarator, it
687applies to the type there.</p>
688
689</div> <!-- ownership.spelling -->
690
691<div id="ownership.semantics">
692<h1>Semantics</h1>
693
694<p>There are five <span class="term">managed operations</span> which
695may be performed on an object of retainable object pointer type. Each
696qualifier specifies different semantics for each of these operations.
697It is still undefined behavior to access an object outside of its
698lifetime.</p>
699
700<p>A load or store with <q>primitive semantics</q> has the same
701semantics as the respective operation would have on an <tt>void*</tt>
702lvalue with the same alignment and non-ownership qualification.</p>
703
704<p><span class="term">Reading</span> occurs when performing a
705lvalue-to-rvalue conversion on an object lvalue.
706
707<ul>
708<li>For <tt>__weak</tt> objects, the current pointee is retained and
709then released at the end of the current full-expression. This must
710execute atomically with respect to assignments and to the final
711release of the pointee.</li>
712<li>For all other objects, the lvalue is loaded with primitive
713semantics.</li>
714</ul>
715</p>
716
717<p><span class="term">Assignment</span> occurs when evaluating
718an assignment operator. The semantics vary based on the qualification:
719<ul>
720<li>For <tt>__strong</tt> objects, the new pointee is first retained;
721second, the lvalue is loaded with primitive semantics; third, the new
722pointee is stored into the lvalue with primitive semantics; and
723finally, the old pointee is released. This is not performed
724atomically; external synchronization must be used to make this safe in
725the face of concurrent loads and stores.</li>
726<li>For <tt>__weak</tt> objects, the lvalue is updated to point to the
727new pointee, unless that object is currently undergoing deallocation,
728in which case it the lvalue is updated to a null pointer. This must
729execute atomically with respect to other assignments to the object, to
730reads from the object, and to the final release of the new pointed-to
John McCall2fad7832011-07-07 00:03:42 +0000731value.</li>
John McCall82467022011-06-15 21:21:53 +0000732<li>For <tt>__unsafe_unretained</tt> objects, the new pointee is
733stored into the lvalue using primitive semantics.</li>
734<li>For <tt>__autoreleasing</tt> objects, the new pointee is retained,
735autoreleased, and stored into the lvalue using primitive semantics.</li>
736</ul>
737</p>
738
739<p><span class="term">Initialization</span> occurs when an object's
740lifetime begins, which depends on its storage duration.
741Initialization proceeds in two stages:
742<ol>
743<li>First, a null pointer is stored into the lvalue using primitive
744semantics. This step is skipped if the object
745is <tt>__unsafe_unretained</tt>.</li>
746<li>Second, if the object has an initializer, that expression is
747evaluated and then assigned into the object using the usual assignment
748semantics.</li>
749</ol>
750</p>
751
752<p><span class="term">Destruction</span> occurs when an object's
753lifetime ends. In all cases it is semantically equivalent to
754assigning a null pointer to the object, with the proviso that of
755course the object cannot be legally read after the object's lifetime
756ends.</p>
757
758<p><span class="term">Moving</span> occurs in specific situations
759where an lvalue is <q>moved from</q>, meaning that its current pointee
760will be used but the object may be left in a different (but still
761valid) state. This arises with <tt>__block</tt> variables and rvalue
762references in C++. For <tt>__strong</tt> lvalues, moving is equivalent
763to loading the lvalue with primitive semantics, writing a null pointer
764to it with primitive semantics, and then releasing the result of the
765load at the end of the current full-expression. For all other
766lvalues, moving is equivalent to reading the object.</p>
767
768</div> <!-- ownership.semantics -->
769
770<div id="ownership.restrictions">
771<h1>Restrictions</h1>
772
John McCall2fad7832011-07-07 00:03:42 +0000773<div id="ownership.restrictions.weak">
774<h1>Weak-unavailable types</h1>
775
776<p>It is explicitly permitted for Objective-C classes to not
777support <tt>__weak</tt> references. It is undefined behavior to
778perform an operation with weak assignment semantics with a pointer to
779an Objective-C object whose class does not support <tt>__weak</tt>
780references.</p>
781
782<div class="rationale"><p>Rationale: historically, it has been
783possible for a class to provide its own reference-count implementation
784by overriding <tt>retain</tt>, <tt>release</tt>, etc. However, weak
785references to an object require coordination with its class's
786reference-count implementation because, among other things, weak loads
787and stores must be atomic with respect to the final release.
788Therefore, existing custom reference-count implementations will
789generally not support weak references without additional effort. This
790is unavoidable without breaking binary compatibility.</p></div>
791
792<p>A class may indicate that it does not support weak references by
793providing the <tt>objc_arc_weak_unavailable</tt> attribute on the
794class's interface declaration. A retainable object pointer type
795is <span class="term">weak-unavailable</span> if is a pointer to an
796(optionally protocol-qualified) Objective-C class <tt>T</tt>
797where <tt>T</tt> or one of its superclasses has
798the <tt>objc_arc_weak_unavailable</tt> attribute. A program is
799ill-formed if it applies the <tt>__weak</tt> ownership qualifier to a
800weak-unavailable type or if the value operand of a weak assignment
801operation has a weak-unavailable type.</p>
802</div> <!-- ownership.restrictions.weak -->
803
John McCall82467022011-06-15 21:21:53 +0000804<div id="ownership.restrictions.autoreleasing">
John McCall2fad7832011-07-07 00:03:42 +0000805<h1>Storage duration of <tt>__autoreleasing</tt> objects</h1>
John McCall82467022011-06-15 21:21:53 +0000806
807<p>A program is ill-formed if it declares an <tt>__autoreleasing</tt>
808object of non-automatic storage duration.</p>
809
810<div class="rationale"><p>Rationale: autorelease pools are tied to the
811current thread and scope by their nature. While it is possible to
812have temporary objects whose instance variables are filled with
813autoreleased objects, there is no way that ARC can provide any sort of
814safety guarantee there.</p></div>
815
816<p>It is undefined behavior if a non-null pointer is assigned to
817an <tt>__autoreleasing</tt> object while an autorelease pool is in
818scope and then that object is read after the autorelease pool's scope
819is left.</p>
820
821</div>
822
823<div id="ownership.restrictions.conversion.indirect">
824<h1>Conversion of pointers to ownership-qualified types</h1>
825
826<p>A program is ill-formed if an expression of type <tt>T*</tt> is
827converted, explicitly or implicitly, to the type <tt>U*</tt>,
828where <tt>T</tt> and <tt>U</tt> have different ownership
829qualification, unless:
830<ul>
831<li><tt>T</tt> is qualified with <tt>__strong</tt>,
832 <tt>__autoreleasing</tt>, or <tt>__unsafe_unretained</tt>, and
833 <tt>U</tt> is qualified with both <tt>const</tt> and
834 <tt>__unsafe_unretained</tt>; or</li>
835<li>either <tt>T</tt> or <tt>U</tt> is <tt>cv void</tt>, where
836<tt>cv</tt> is an optional sequence of non-ownership qualifiers; or</li>
837<li>the conversion is requested with a <tt>reinterpret_cast</tt> in
838 Objective-C++; or</li>
839<li>the conversion is a
840well-formed <a href="#ownership.restrictions.pass_by_writeback">pass-by-writeback</a>.</li>
841</ul>
842</p>
843
844<p>The analogous rule applies to <tt>T&</tt> and <tt>U&</tt> in
845Objective-C++.</p>
846
847<div class="rationale"><p>Rationale: these rules provide a reasonable
848level of type-safety for indirect pointers, as long as the underlying
849memory is not deallocated. The conversion to <tt>const
850__unsafe_unretained</tt> is permitted because the semantics of reads
851are equivalent across all these ownership semantics, and that's a very
852useful and common pattern. The interconversion with <tt>void*</tt> is
853useful for allocating memory or otherwise escaping the type system,
854but use it carefully. <tt>reinterpret_cast</tt> is considered to be
855an obvious enough sign of taking responsibility for any
856problems.</p></div>
857
858<p>It is undefined behavior to access an ownership-qualified object
859through an lvalue of a differently-qualified type, except that any
860non-<tt>__weak</tt> object may be read through
861an <tt>__unsafe_unretained</tt> lvalue.</p>
862
863<p>It is undefined behavior if a managed operation is performed on
864a <tt>__strong</tt> or <tt>__weak</tt> object without a guarantee that
865it contains a primitive zero bit-pattern, or if the storage for such
866an object is freed or reused without the object being first assigned a
867null pointer.</p>
868
869<div class="rationale"><p>Rationale: ARC cannot differentiate between
870an assignment operator which is intended to <q>initialize</q> dynamic
871memory and one which is intended to potentially replace a value.
872Therefore the object's pointer must be valid before letting ARC at it.
873Similarly, C and Objective-C do not provide any language hooks for
874destroying objects held in dynamic memory, so it is the programmer's
875responsibility to avoid leaks (<tt>__strong</tt> objects) and
876consistency errors (<tt>__weak</tt> objects).</p>
877
878<p>These requirements are followed automatically in Objective-C++ when
879creating objects of retainable object owner type with <tt>new</tt>
880or <tt>new[]</tt> and destroying them with <tt>delete</tt>,
881<tt>delete[]</tt>, or a pseudo-destructor expression. Note that
882arrays of nontrivially-ownership-qualified type are not ABI compatible
883with non-ARC code because the element type is non-POD: such arrays
884that are <tt>new[]</tt>'d in ARC translation units cannot
885be <tt>delete[]</tt>'d in non-ARC translation units and
886vice-versa.</p></div>
887
888</div>
889
890<div id="ownership.restrictions.pass_by_writeback">
891<h1>Passing to an out parameter by writeback</h1>
892
893<p>If the argument passed to a parameter of type
894<tt>T __autoreleasing *</tt> has type <tt>U oq *</tt>,
895where <tt>oq</tt> is an ownership qualifier, then the argument is a
896candidate for <span class="term">pass-by-writeback</span> if:</p>
897
898<ul>
899<li><tt>oq</tt> is <tt>__strong</tt> or <tt>__weak</tt>, and
900<li>it would be legal to initialize a <tt>T __strong *</tt> with
901a <tt>U __strong *</tt>.</li>
902</ul>
903
904<p>For purposes of overload resolution, an implicit conversion
905sequence requiring a pass-by-writeback is always worse than an
906implicit conversion sequence not requiring a pass-by-writeback.</p>
907
908<p>The pass-by-writeback is ill-formed if the argument expression does
909not have a legal form:</p>
910
911<ul>
912<li><tt>&var</tt>, where <tt>var</tt> is a scalar variable of
913automatic storage duration with retainable object pointer type</li>
914<li>a conditional expression where the second and third operands are
915both legal forms</li>
916<li>a cast whose operand is a legal form</li>
917<li>a null pointer constant</li>
918</ul>
919
920<div class="rationale"><p>Rationale: the restriction in the form of
921the argument serves two purposes. First, it makes it impossible to
922pass the address of an array to the argument, which serves to protect
923against an otherwise serious risk of mis-inferring an <q>array</q>
924argument as an out-parameter. Second, it makes it much less likely
925that the user will see confusing aliasing problems due to the
926implementation, below, where their store to the writeback temporary is
927not immediately seen in the original argument variable.</p></div>
928
929<p>A pass-by-writeback is evaluated as follows:
930<ol>
931<li>The argument is evaluated to yield a pointer <tt>p</tt> of
932 type <tt>U oq *</tt>.</li>
933<li>If <tt>p</tt> is a null pointer, then a null pointer is passed as
934 the argument, and no further work is required for the pass-by-writeback.</li>
935<li>Otherwise, a temporary of type <tt>T __autoreleasing</tt> is
936 created and initialized to a null pointer.</li>
937<li>If the argument is not an Objective-C method parameter marked
938 <tt>out</tt>, then <tt>*p</tt> is read, and the result is written
939 into the temporary with primitive semantics.</li>
940<li>The address of the temporary is passed as the argument to the
941 actual call.</li>
942<li>After the call completes, the temporary is loaded with primitive
943 semantics, and that value is assigned into <tt>*p</tt>.</li>
944</ol></p>
945
946<div class="rationale"><p>Rationale: this is all admittedly
947convoluted. In an ideal world, we would see that a local variable is
948being passed to an out-parameter and retroactively modify its type to
949be <tt>__autoreleasing</tt> rather than <tt>__strong</tt>. This would
950be remarkably difficult and not always well-founded under the C type
951system. However, it was judged unacceptably invasive to require
952programmers to write <tt>__autoreleasing</tt> on all the variables
953they intend to use for out-parameters. This was the least bad
954solution.</p></div>
955
956</div>
957
958<div id="ownership.restrictions.records">
959<h1>Ownership-qualified fields of structs and unions</h1>
960
961<p>A program is ill-formed if it declares a member of a C struct or
962union to have a nontrivially ownership-qualified type.</p>
963
964<div class="rationale"><p>Rationale: the resulting type would be
965non-POD in the C++ sense, but C does not give us very good language
966tools for managing the lifetime of aggregates, so it is more
967convenient to simply forbid them. It is still possible to manage this
968with a <tt>void*</tt> or an <tt>__unsafe_unretained</tt>
969object.</p></div>
970
971<p>This restriction does not apply in Objective-C++. However,
972nontrivally ownership-qualified types are considered non-POD: in C++0x
973terms, they are not trivially default constructible, copy
974constructible, move constructible, copy assignable, move assignable,
975or destructible. It is a violation of C++ One Definition Rule to use
976a class outside of ARC that, under ARC, would have an
977ownership-qualified member.</p>
978
979<div class="rationale"><p>Rationale: unlike in C, we can express all
980the necessary ARC semantics for ownership-qualified subobjects as
981suboperations of the (default) special member functions for the class.
982These functions then become non-trivial. This has the non-obvious
983repercussion that the class will have a non-trivial copy constructor
984and non-trivial destructor; if it wouldn't outside of ARC, this means
985that objects of the type will be passed and returned in an
986ABI-incompatible manner.</p></div>
987
988</div>
989
990</div>
991
992<div id="ownership.inference">
993<h1>Ownership inference</h1>
994
995<div id="ownership.inference.variables">
996<h1>Objects</h1>
997
998<p>If an object is declared with retainable object owner type, but
999without an explicit ownership qualifier, its type is implicitly
1000adjusted to have <tt>__strong</tt> qualification.</p>
1001
1002<p>As a special case, if the object's base type is <tt>Class</tt>
1003(possibly protocol-qualified), the type is adjusted to
1004have <tt>__unsafe_unretained</tt> qualification instead.</p>
1005
1006</div>
1007
1008<div id="ownership.inference.indirect_parameters">
1009<h1>Indirect parameters</h1>
1010
1011<p>If a function or method parameter has type <tt>T*</tt>, where
1012<tt>T</tt> is an ownership-unqualified retainable object pointer type,
1013then:</p>
1014
1015<ul>
1016<li>if <tt>T</tt> is <tt>const</tt>-qualified or <tt>Class</tt>, then
1017it is implicitly qualified with <tt>__unsafe_unretained</tt>;</li>
1018<li>otherwise, it is implicitly qualified
1019with <tt>__autoreleasing</tt>.</li>
1020</ul>
1021</p>
1022
1023<div class="rationale"><p>Rationale: <tt>__autoreleasing</tt> exists
1024mostly for this case, the Cocoa convention for out-parameters. Since
1025a pointer to <tt>const</tt> is obviously not an out-parameter, we
1026instead use a type more useful for passing arrays. If the user
1027instead intends to pass in a <em>mutable</em> array, inferring
1028<tt>__autoreleasing</tt> is the wrong thing to do; this directs some
1029of the caution in the following rules about writeback.</p></div>
1030
1031<p>Such a type written anywhere else would be ill-formed by the
1032general rule requiring ownership qualifiers.</p>
1033
1034<p>This rule does not apply in Objective-C++ if a parameter's type is
1035dependent in a template pattern and is only <em>instantiated</em> to
1036a type which would be a pointer to an unqualified retainable object
1037pointer type. Such code is still ill-formed.</p>
1038
1039<div class="rationale"><p>Rationale: the convention is very unlikely
1040to be intentional in template code.</p></div>
1041
1042</div> <!-- ownership.inference.indirect_parameters -->
Douglas Gregore559ca12011-06-17 22:11:49 +00001043
1044<div id="ownership.inference.template_arguments">
1045<h1>Template arguments</h1>
1046
1047<p>If a template argument for a template type parameter is an
1048retainable object owner type that does not have an explicit ownership
1049qualifier, it is adjusted to have <tt>__strong</tt>
Douglas Gregor54fb28a2011-06-17 22:19:27 +00001050qualification. This adjustment occurs regardless of whether the
Douglas Gregore559ca12011-06-17 22:11:49 +00001051template argument was deduced or explicitly specified. </p>
1052
1053<div class="rationale"><p>Rationale: <tt>__strong</tt> is a useful default for containers (e.g., <tt>std::vector&lt;id&gt;</tt>), which would otherwise require explicit qualification. Moreover, unqualified retainable object pointer types are unlikely to be useful within templates, since they generally need to have a qualifier applied to the before being used.</p></div>
1054
1055</div> <!-- ownership.inference.template_arguments -->
John McCall82467022011-06-15 21:21:53 +00001056</div> <!-- ownership.inference -->
1057</div> <!-- ownership -->
1058
Douglas Gregore559ca12011-06-17 22:11:49 +00001059
John McCall82467022011-06-15 21:21:53 +00001060<div id="family">
1061<h1>Method families</h1>
1062
1063<p>An Objective-C method may fall into a <span class="term">method
1064family</span>, which is a conventional set of behaviors ascribed to it
1065by the Cocoa conventions.</p>
1066
1067<p>A method is in a certain method family if:
1068<ul>
1069<li>it has a <tt>objc_method_family</tt> attribute placing it in that
1070 family; or if not that,</li>
1071<li>it does not have an <tt>objc_method_family</tt> attribute placing
1072 it in a different or no family, and</li>
1073<li>its selector falls into the corresponding selector family, and</li>
1074<li>its signature obeys the added restrictions of the method family.</li>
1075</ul></p>
1076
1077<p>A selector is in a certain selector family if, ignoring any leading
1078underscores, the first component of the selector either consists
1079entirely of the name of the method family or it begins with that name
1080followed by a character other than a lowercase letter. For
1081example, <tt>_perform:with:</tt> and <tt>performWith:</tt> would fall
1082into the <tt>perform</tt> family (if we recognized one),
1083but <tt>performing:with</tt> would not.</p>
1084
1085<p>The families and their added restrictions are:</p>
1086
1087<ul>
1088<li><tt>alloc</tt> methods must return a retainable object pointer type.</li>
1089<li><tt>copy</tt> methods must return a retainable object pointer type.</li>
1090<li><tt>mutableCopy</tt> methods must return a retainable object pointer type.</li>
1091<li><tt>new</tt> methods must return a retainable object pointer type.</li>
1092<li><tt>init</tt> methods must be instance methods and must return an
1093Objective-C pointer type. Additionally, a program is ill-formed if it
1094declares or contains a call to an <tt>init</tt> method whose return
1095type is neither <tt>id</tt> nor a pointer to a super-class or
John McCallbe16b892011-06-18 08:15:19 +00001096sub-class of the declaring class (if the method was declared on
1097a class) or the static receiver type of the call (if it was declared
1098on a protocol).</p>
John McCall82467022011-06-15 21:21:53 +00001099
1100<div class="rationale"><p>Rationale: there are a fair number of existing
1101methods with <tt>init</tt>-like selectors which nonetheless don't
1102follow the <tt>init</tt> conventions. Typically these are either
1103accidental naming collisions or helper methods called during
1104initialization. Because of the peculiar retain/release behavior
1105of <tt>init</tt> methods, it's very important not to treat these
1106methods as <tt>init</tt> methods if they aren't meant to be. It was
1107felt that implicitly defining these methods out of the family based on
1108the exact relationship between the return type and the declaring class
John McCallbe16b892011-06-18 08:15:19 +00001109would be much too subtle and fragile. Therefore we identify a small
John McCall82467022011-06-15 21:21:53 +00001110number of legitimate-seeming return types and call everything else an
1111error. This serves the secondary purpose of encouraging programmers
John McCallbe16b892011-06-18 08:15:19 +00001112not to accidentally give methods names in the <tt>init</tt> family.</p>
1113
1114<p>Note that a method with an <tt>init</tt>-family selector which
1115returns a non-Objective-C type (e.g. <tt>void</tt>) is perfectly
1116well-formed; it simply isn't in the <tt>init</tt> family.</p></div>
John McCall82467022011-06-15 21:21:53 +00001117</li>
1118</ul>
1119
1120<p>A program is ill-formed if a method's declarations,
1121implementations, and overrides do not all have the same method
1122family.</p>
1123
1124<div id="family.attribute">
1125<h1>Explicit method family control</h1>
1126
1127<p>A method may be annotated with the <tt>objc_method_family</tt>
1128attribute to precisely control which method family it belongs to. If
1129a method in an <tt>@implementation</tt> does not have this attribute,
1130but there is a method declared in the corresponding <tt>@interface</tt>
1131that does, then the attribute is copied to the declaration in the
1132<tt>@implementation</tt>. The attribute is available outside of ARC,
1133and may be tested for with the preprocessor query
1134<tt>__has_attribute(objc_method_family)</tt>.</p>
1135
1136<p>The attribute is spelled
1137<tt>__attribute__((objc_method_family(<i>family</i>)))</tt>.
1138If <i>family</i> is <tt>none</tt>, the method has no family, even if
1139it would otherwise be considered to have one based on its selector and
1140type. Otherwise, <i>family</i> must be one
1141of <tt>alloc</tt>, <tt>copy</tt>, <tt>init</tt>,
1142<tt>mutableCopy</tt>, or <tt>new</tt>, in which case the method is
1143considered to belong to the corresponding family regardless of its
1144selector. It is an error if a method that is explicitly added to a
1145family in this way does not meet the requirements of the family other
1146than the selector naming convention.</p>
1147
1148<div class="rationale"><p>Rationale: the rules codified in this document
1149describe the standard conventions of Objective-C. However, as these
1150conventions have not heretofore been enforced by an unforgiving
1151mechanical system, they are only imperfectly kept, especially as they
1152haven't always even been precisely defined. While it is possible to
1153define low-level ownership semantics with attributes like
1154<tt>ns_returns_retained</tt>, this attribute allows the user to
1155communicate semantic intent, which of use both to ARC (which, e.g.,
1156treats calls to <tt>init</tt> specially) and the static analyzer.</p></div>
1157</div>
1158
1159<div id="family.semantics">
1160<h1>Semantics of method families</h1>
1161
1162<p>A method's membership in a method family may imply non-standard
1163semantics for its parameters and return type.</p>
1164
1165<p>Methods in the <tt>alloc</tt>, <tt>copy</tt>, <tt>mutableCopy</tt>,
1166and <tt>new</tt> families &mdash; that is, methods in all the
John McCallbe16b892011-06-18 08:15:19 +00001167currently-defined families except <tt>init</tt> &mdash; implicitly
1168<a href="#objects.operands.retained_returns">return a retained
1169object</a> as if they were annotated with
1170the <tt>ns_returns_retained</tt> attribute. This can be overridden by
1171annotating the method with either of
1172the <tt>ns_returns_autoreleased</tt> or
John McCall82467022011-06-15 21:21:53 +00001173<tt>ns_returns_not_retained</tt> attributes.</p>
1174
Fariborz Jahanianacd4aaf2011-07-06 22:47:46 +00001175<p>Properties also follow same naming rules as methods. This means that
1176those in the <tt>alloc</tt>, <tt>copy</tt>, <tt>mutableCopy</tt>,
1177and <tt>new</tt> families provide access to
1178<a href="#objects.operands.retained_returns">retained objects</a>.
1179This can be overridden by annotating the property with
1180<tt>ns_returns_not_retained</tt> attribute.</p>
1181
John McCall82467022011-06-15 21:21:53 +00001182<div id="family.semantics.init">
1183<h1>Semantics of <tt>init</tt></h1>
John McCallbe16b892011-06-18 08:15:19 +00001184<p>Methods in the <tt>init</tt> family implicitly
1185<a href="#objects.operands.consumed">consume</a> their <tt>self</tt>
1186parameter and <a href="#objects.operands.retained_returns">return a
1187retained object</a>. Neither of these properties can be altered
1188through attributes.</p>
John McCall82467022011-06-15 21:21:53 +00001189
1190<p>A call to an <tt>init</tt> method with a receiver that is either
1191<tt>self</tt> (possibly parenthesized or casted) or <tt>super</tt> is
1192called a <span class="term">delegate init call</span>. It is an error
1193for a delegate init call to be made except from an <tt>init</tt>
1194method, and excluding blocks within such methods.</p>
1195
John McCallbe16b892011-06-18 08:15:19 +00001196<p>As an exception to the <a href="misc.self">usual rule</a>, the
1197variable <tt>self</tt> is mutable in an <tt>init</tt> method and has
1198the usual semantics for a <tt>__strong</tt> variable. However, it is
1199undefined behavior and the program is ill-formed, no diagnostic
1200required, if an <tt>init</tt> method attempts to use the previous
1201value of <tt>self</tt> after the completion of a delegate init call.
1202It is conventional, but not required, for an <tt>init</tt> method to
1203return <tt>self</tt>.</p>
John McCall82467022011-06-15 21:21:53 +00001204
John McCallbe16b892011-06-18 08:15:19 +00001205<p>It is undefined behavior for a program to cause two or more calls
1206to <tt>init</tt> methods on the same object, except that
1207each <tt>init</tt> method invocation may perform at most one delegate
1208init call.</p>
John McCall82467022011-06-15 21:21:53 +00001209
John McCallf3d08a62011-06-18 07:31:30 +00001210</div> <!-- family.semantics.init -->
John McCall82467022011-06-15 21:21:53 +00001211
1212<div id="family.semantics.result_type">
1213<h1>Related result types</h1>
1214
1215<p>Certain methods are candidates to have <span class="term">related
1216result types</span>:</p>
1217<ul>
1218<li>class methods in the <tt>alloc</tt> and <tt>new</tt> method families</li>
1219<li>instance methods in the <tt>init</tt> family</li>
1220<li>the instance method <tt>self</tt></li>
1221<li>outside of ARC, the instance methods <tt>retain</tt> and <tt>autorelease</tt></li>
1222</ul>
1223
1224<p>If the formal result type of such a method is <tt>id</tt> or
1225protocol-qualified <tt>id</tt>, or a type equal to the declaring class
1226or a superclass, then it is said to have a related result type. In
1227this case, when invoked in an explicit message send, it is assumed to
1228return a type related to the type of the receiver:</p>
1229
1230<ul>
1231<li>if it is a class method, and the receiver is a class
1232name <tt>T</tt>, the message send expression has type <tt>T*</tt>;
1233otherwise</li>
1234<li>if it is an instance method, and the receiver has type <tt>T</tt>,
1235the message send expression has type <tt>T</tt>; otherwise</li>
1236<li>the message send expression has the normal result type of the
1237method.</li>
1238</ul>
1239
1240<p>This is a new rule of the Objective-C language and applies outside
1241of ARC.</p>
1242
1243<div class="rationale"><p>Rationale: ARC's automatic code emission is
1244more prone than most code to signature errors, i.e. errors where a
1245call was emitted against one method signature, but the implementing
1246method has an incompatible signature. Having more precise type
1247information helps drastically lower this risks, as well as catching
1248a number of latent bugs.</p></div>
1249
1250</div> <!-- family.semantics.result_type -->
1251</div> <!-- family.semantics -->
1252</div> <!-- family -->
1253
1254<div id="optimization">
1255<h1>Optimization</h1>
1256
1257<p>ARC applies aggressive rules for the optimization of local
1258behavior. These rules are based around a core assumption of
1259<span class="term">local balancing</span>: that other code will
1260perform retains and releases as necessary (and only as necessary) for
1261its own safety, and so the optimizer does not need to consider global
1262properties of the retain and release sequence. For example, if a
1263retain and release immediately bracket a call, the optimizer can
1264delete the retain and release on the assumption that the called
1265function will not do a constant number of unmotivated releases
1266followed by a constant number of <q>balancing</q> retains, such that
1267the local retain/release pair is the only thing preventing the called
1268function from ending up with a dangling reference.</p>
1269
1270<p>The optimizer assumes that when a new value enters local control,
1271e.g. from a load of a non-local object or as the result of a function
1272call, it is instaneously valid. Subsequently, a retain and release of
1273a value are necessary on a computation path only if there is a use of
1274that value before the release and after any operation which might
1275cause a release of the value (including indirectly or non-locally),
1276and only if the value is not demonstrably already retained.</p>
1277
1278<p>The complete optimization rules are quite complicated, but it would
1279still be useful to document them here.</p>
1280
1281</div>
1282
1283<div id="misc">
1284<h1>Miscellaneous</h1>
1285
John McCallf3d08a62011-06-18 07:31:30 +00001286<div id="misc.special_methods">
1287<h1>Special methods</h1>
1288
1289<div id="misc.special_methods.retain">
1290<h1>Memory management methods</h1>
1291
1292<p>A program is ill-formed if it contains a method definition, message
1293send, or <tt>@selector</tt> expression for any of the following
1294selectors:
1295<ul>
1296<li><tt>autorelease</tt></li>
1297<li><tt>release</tt></li>
1298<li><tt>retain</tt></li>
1299<li><tt>retainCount</tt></li>
1300</ul>
1301</p>
1302
1303<div class="rationale"><p>Rationale: <tt>retainCount</tt> is banned
1304because ARC robs it of consistent semantics. The others were banned
1305after weighing three options for how to deal with message sends:</p>
1306
1307<p><b>Honoring</b> them would work out very poorly if a programmer
1308naively or accidentally tried to incorporate code written for manual
1309retain/release code into an ARC program. At best, such code would do
1310twice as much work as necessary; quite frequently, however, ARC and
1311the explicit code would both try to balance the same retain, leading
1312to crashes. The cost is losing the ability to perform <q>unrooted</q>
1313retains, i.e. retains not logically corresponding to a strong
1314reference in the object graph.</p>
1315
1316<p><b>Ignoring</b> them would badly violate user expectations about their
1317code. While it <em>would</em> make it easier to develop code simultaneously
1318for ARC and non-ARC, there is very little reason to do so except for
1319certain library developers. ARC and non-ARC translation units share
1320an execution model and can seamlessly interoperate. Within a
1321translation unit, a developer who faithfully maintains their code in
1322non-ARC mode is suffering all the restrictions of ARC for zero
1323benefit, while a developer who isn't testing the non-ARC mode is
1324likely to be unpleasantly surprised if they try to go back to it.</p>
1325
1326<p><b>Banning</b> them has the disadvantage of making it very awkward
1327to migrate existing code to ARC. The best answer to that, given a
1328number of other changes and restrictions in ARC, is to provide a
1329specialized tool to assist users in that migration.</p>
1330
1331<p>Implementing these methods was banned because they are too integral
1332to the semantics of ARC; many tricks which worked tolerably under
1333manual reference counting will misbehave if ARC performs an ephemeral
1334extra retain or two. If absolutely required, it is still possible to
1335implement them in non-ARC code, for example in a category; the
1336implementations must obey the <a href="#objects.retains">semantics</a>
1337laid out elsewhere in this document.</p>
1338
1339</div>
1340</div> <!-- misc.special_methods.retain -->
1341
1342<div id="misc.special_methods.dealloc">
1343<h1><tt>dealloc</tt></h1>
1344
1345<p>A program is ill-formed if it contains a message send
1346or <tt>@selector</tt> expression for the selector <tt>dealloc</tt>.</p>
1347
1348<div class="rationale"><p>Rationale: there are no legitimate reasons
1349to call <tt>dealloc</tt> directly.</p></div>
1350
1351<p>A class may provide a method definition for an instance method
1352named <tt>dealloc</tt>. This method will be called after the final
1353<tt>release</tt> of the object but before it is deallocated or any of
1354its instance variables are destroyed. The superclass's implementation
1355of <tt>dealloc</tt> will be called automatically when the method
1356returns.</p>
1357
1358<div class="rationale"><p>Rationale: even though ARC destroys instance
1359variables automatically, there are still legitimate reasons to write
1360a <tt>dealloc</tt> method, such as freeing non-retainable resources.
1361Failing to call <tt>[super&nbsp;dealloc]</tt> in such a method is nearly
1362always a bug. Sometimes, the object is simply trying to prevent
1363itself from being destroyed, but <tt>dealloc</tt> is really far too
1364late for the object to be raising such objections. Somewhat more
1365legitimately, an object may have been pool-allocated and should not be
1366deallocated with <tt>free</tt>; for now, this can only be supported
1367with a <tt>dealloc</tt> implementation outside of ARC. Such an
1368implementation must be very careful to do all the other work
1369that <tt>NSObject</tt>'s <tt>dealloc</tt> would, which is outside the
1370scope of this document to describe.</p></div>
1371
1372</div>
1373
1374</div> <!-- misc.special_methods -->
1375
John McCall82467022011-06-15 21:21:53 +00001376<div id="autoreleasepool">
1377<h1><tt>@autoreleasepool</tt></h1>
1378
1379<p>To simplify the use of autorelease pools, and to bring them under
1380the control of the compiler, a new kind of statement is available in
1381Objective-C. It is written <tt>@autoreleasepool</tt> followed by
1382a <i>compound-statement</i>, i.e. by a new scope delimited by curly
1383braces. Upon entry to this block, the current state of the
1384autorelease pool is captured. When the block is exited normally,
1385whether by fallthrough or directed control flow (such
1386as <tt>return</tt> or <tt>break</tt>), the autorelease pool is
1387restored to the saved state, releasing all the objects in it. When
1388the block is exited with an exception, the pool is not drained.</p>
1389
John McCallf3d08a62011-06-18 07:31:30 +00001390<p><tt>@autoreleasepool</tt> may be used in non-ARC translation units,
1391with equivalent semantics.</p>
1392
John McCall82467022011-06-15 21:21:53 +00001393<p>A program is ill-formed if it refers to the
1394<tt>NSAutoreleasePool</tt> class.</p>
1395
1396<div class="rationale"><p>Rationale: autorelease pools are clearly
1397important for the compiler to reason about, but it is far too much to
1398expect the compiler to accurately reason about control dependencies
1399between two calls. It is also very easy to accidentally forget to
1400drain an autorelease pool when using the manual API, and this can
1401significantly inflate the process's high-water-mark. The introduction
1402of a new scope is unfortunate but basically required for sane
1403interaction with the rest of the language. Not draining the pool
1404during an unwind is apparently required by the Objective-C exceptions
1405implementation.</p></div>
1406
1407</div> <!-- autoreleasepool -->
1408
1409<div id="misc.self">
1410<h1><tt>self</tt></h1>
1411
1412<p>The <tt>self</tt> parameter variable of an Objective-C method is
1413never actually retained by the implementation. It is undefined
1414behavior, or at least dangerous, to cause an object to be deallocated
1415during a message send to that object. To make this
1416safe, <tt>self</tt> is implicitly <tt>const</tt> unless the method is
1417in the <a href="#family.semantics.init"><tt>init</tt> family</a>.</p>
1418
1419<div class="rationale"><p>Rationale: the cost of
1420retaining <tt>self</tt> in all methods was found to be prohibitive, as
1421it tends to be live across calls, preventing the optimizer from
1422proving that the retain and release are unnecessary &mdash; for good
1423reason, as it's quite possible in theory to cause an object to be
1424deallocated during its execution without this retain and release.
1425Since it's extremely uncommon to actually do so, even unintentionally,
1426and since there's no natural way for the programmer to remove this
1427retain/release pair otherwise (as there is for other parameters by,
1428say, making the variable <tt>__unsafe_unretained</tt>), we chose to
1429make this optimizing assumption and shift some amount of risk to the
1430user.</p></div>
1431
1432</div> <!-- misc.self -->
1433
1434<div id="misc.enumeration">
1435<h1>Fast enumeration iteration variables</h1>
1436
1437<p>If a variable is declared in the condition of an Objective-C fast
1438enumeration loop, and the variable has no explicit ownership
1439qualifier, then it is qualified with <tt>const __strong</tt> and
1440objects encountered during the enumeration are not actually
1441retained.</p>
1442
1443<div class="rationale"><p>Rationale: this is an optimization made
1444possible because fast enumeration loops promise to keep the objects
1445retained during enumeration, and the collection itself cannot be
1446synchronously modified. It can be overridden by explicitly qualifying
1447the variable with <tt>__strong</tt>, which will make the variable
1448mutable again and cause the loop to retain the objects it
1449encounters.</div>
1450
1451</div>
1452
1453<div id="misc.blocks">
1454<h1>Blocks</h1>
1455
1456<p>The implicit <tt>const</tt> capture variables created when
1457evaluating a block literal expression have the same ownership
1458semantics as the local variables they capture. The capture is
1459performed by reading from the captured variable and initializing the
1460capture variable with that value; the capture variable is destroyed
1461when the block literal is, i.e. at the end of the enclosing scope.</p>
1462
1463<p>The <a href="#ownership.inference">inference</a> rules apply
1464equally to <tt>__block</tt> variables, which is a shift in semantics
1465from non-ARC, where <tt>__block</tt> variables did not implicitly
1466retain during capture.</p>
1467
1468<p><tt>__block</tt> variables of retainable object owner type are
1469moved off the stack by initializing the heap copy with the result of
1470moving from the stack copy.</tt></p>
1471
1472<p>With the exception of retains done as part of initializing
1473a <tt>__strong</tt> parameter variable or reading a <tt>__weak</tt>
1474variable, whenever these semantics call for retaining a value of
1475block-pointer type, it has the effect of a <tt>Block_copy</tt>. The
1476optimizer may remove such copies when it sees that the result is
1477used only as an argument to a call.</p>
1478
1479</div> <!-- misc.blocks -->
1480
1481<div id="misc.exceptions">
1482<h1>Exceptions</h1>
1483
1484<p>By default in Objective C, ARC is not exception-safe for normal
1485releases:
1486<ul>
1487<li>It does not end the lifetime of <tt>__strong</tt> variables when
1488their scopes are abnormally terminated by an exception.</li>
1489<li>It does not perform releases which would occur at the end of
1490a full-expression if that full-expression throws an exception.</li>
1491</ul>
1492
1493<p>A program may be compiled with the option
1494<tt>-fobjc-arc-exceptions</tt> in order to enable these, or with the
1495option <tt>-fno-objc-arc-exceptions</tt> to explicitly disable them,
1496with the last such argument <q>winning</q>.</p>
1497
1498<div class="rationale"><p>Rationale: the standard Cocoa convention is
1499that exceptions signal programmer error and are not intended to be
1500recovered from. Making code exceptions-safe by default would impose
1501severe runtime and code size penalties on code that typically does not
1502actually care about exceptions safety. Therefore, ARC-generated code
1503leaks by default on exceptions, which is just fine if the process is
1504going to be immediately terminated anyway. Programs which do care
1505about recovering from exceptions should enable the option.</p></div>
1506
1507<p>In Objective-C++, <tt>-fobjc-arc-exceptions</tt> is enabled by
1508default.</p>
1509
1510<div class="rationale"><p>Rationale: C++ already introduces pervasive
1511exceptions-cleanup code of the sort that ARC introduces. C++
1512programmers who have not already disabled exceptions are much more
1513likely to actual require exception-safety.</p></div>
1514
1515<p>ARC does end the lifetimes of <tt>__weak</tt> objects when an
1516exception terminates their scope unless exceptions are disabled in the
1517compiler.</p>
1518
1519<div class="rationale"><p>Rationale: the consequence of a
1520local <tt>__weak</tt> object not being destroyed is very likely to be
1521corruption of the Objective-C runtime, so we want to be safer here.
1522Of course, potentially massive leaks are about as likely to take down
1523the process as this corruption is if the program does try to recover
1524from exceptions.</p></div>
1525
1526</div> <!-- misc.exceptions -->
1527
1528</div> <!-- misc -->
John McCall98a48cf2011-06-19 09:36:02 +00001529
1530<div id="runtime">
1531<h1>Runtime support</h1>
1532
John McCall085d09d2011-06-19 10:12:24 +00001533<p>This section describes the interaction between the ARC runtime and
1534the code generated by the ARC compiler. This is not part of the ARC
1535language specification; instead, it is effectively a language-specific
1536ABI supplement, akin to the <q>Itanium</q> generic ABI for C++.</p>
John McCall98a48cf2011-06-19 09:36:02 +00001537
1538<p>Ownership qualification does not alter the storage requirements for
John McCall085d09d2011-06-19 10:12:24 +00001539objects, except that it is undefined behavior if a <tt>__weak</tt>
1540object is inadequately aligned for an object of type <tt>id</tt>. The
1541other qualifiers may be used on explicitly under-aligned memory.</p>
John McCall98a48cf2011-06-19 09:36:02 +00001542
1543<p>The runtime tracks <tt>__weak</tt> objects which holds non-null
John McCall3914a302011-06-19 09:59:33 +00001544values. It is undefined behavior to direct modify a <tt>__weak</tt>
1545object which is being tracked by the runtime except through an
1546<a href="#runtime.objc_storeWeak"><tt>objc_storeWeak</tt></a>,
1547<a href="#runtime.objc_destroyWeak"><tt>objc_destroyWeak</tt></a>,
1548or <a href="#runtime.objc_moveWeak"><tt>objc_moveWeak</tt></a>
John McCall98a48cf2011-06-19 09:36:02 +00001549call.</p>
1550
John McCall3914a302011-06-19 09:59:33 +00001551<p>The runtime must provide a number of new entrypoints which the
1552compiler may emit, which are described in the remainder of this
1553section.</p>
1554
1555<div class="rationale"><p>Rationale: Several of these functions are
1556semantically equivalent to a message send; we emit calls to C
1557functions instead because:</p>
1558<ul>
1559<li>the machine code to do so is significantly smaller,</li>
1560<li>it is much easier to recognize the C functions in the ARC optimizer, and</li>
1561<li>a sufficient sophisticated runtime may be able to avoid the
1562message send in common cases.</li>
1563</ul>
1564
1565<p>Several other of these functions are <q>fused</q> operations which
1566can be described entirely in terms of other operations. We use the
1567fused operations primarily as a code-size optimization, although in
1568some cases there is also a real potential for avoiding redundant
1569operations in the runtime.</p>
1570
1571</div>
1572
John McCall98a48cf2011-06-19 09:36:02 +00001573<div id="runtime.objc_autorelease">
1574<h1><tt>id objc_autorelease(id value);</tt></h1>
1575<p><i>Precondition:</i> <tt>value</tt> is null or a pointer to a
1576valid object.</p>
1577<p>If <tt>value</tt> is null, this call has no effect. Otherwise, it
1578adds the object to the innermost autorelease pool exactly as if the
1579object had been sent the <tt>autorelease</tt> message.</p>
1580<p>Always returns <tt>value</tt>.</p>
1581</div> <!-- runtime.objc_autorelease -->
1582
1583<div id="runtime.objc_autoreleasePoolPop">
1584<h1><tt>void objc_autoreleasePoolPop(void *pool);</tt></h1>
1585<p><i>Precondition:</i> <tt>pool</tt> is the result of a previous call to
1586<a href="runtime.objc_autoreleasePoolPush"><tt>objc_autoreleasePoolPush</tt></a>
1587on the current thread, where neither <tt>pool</tt> nor any enclosing
1588pool have previously been popped.</p>
1589<p>Releases all the objects added to the given autorelease pool and
1590any autorelease pools it encloses, then sets the current autorelease
1591pool to the pool directly enclosing <tt>pool</tt>.</p>
1592</div> <!-- runtime.objc_autoreleasePoolPop -->
1593
1594<div id="runtime.objc_autoreleasePoolPush">
1595<h1><tt>void *objc_autoreleasePoolPush(void);</tt></h1>
1596<p>Creates a new autorelease pool that is enclosed by the current
1597pool, makes that the current pool, and returns an opaque <q>handle</q>
1598to it.</p>
1599
1600<div class="rationale"><p>Rationale: while the interface is described
1601as an explicit hierarchy of pools, the rules allow the implementation
1602to just keep a stack of objects, using the stack depth as the opaque
1603pool handle.</p></div>
1604
1605</div> <!-- runtime.objc_autoreleasePoolPush -->
1606
1607<div id="runtime.objc_autoreleaseReturnValue">
1608<h1><tt>id objc_autoreleaseReturnValue(id value);</tt></h1>
1609<p><i>Precondition:</i> <tt>value</tt> is null or a pointer to a
1610valid object.</p>
1611<p>If <tt>value</tt> is null, this call has no effect. Otherwise, it
1612makes a best effort to hand off ownership of a retain count on the
1613object to a call
1614to <a href="runtime.objc_retainAutoreleasedReturnValue"><tt>objc_retainAutoreleasedReturnValue</tt></a>
1615for the same object in an enclosing call frame. If this is not
1616possible, the object is autoreleased as above.</p>
1617<p>Always returns <tt>value</tt>.</p>
1618</div> <!-- runtime.objc_autoreleaseReturnValue -->
1619
1620<div id="runtime.objc_copyWeak">
1621<h1><tt>void objc_copyWeak(id *dest, id *src);</tt></h1>
1622<p><i>Precondition:</i> <tt>src</tt> is a valid pointer which either
1623contains a null pointer or has been registered as a <tt>__weak</tt>
1624object. <tt>dest</tt> is a valid pointer which has not been
1625registered as a <tt>__weak</tt> object.</p>
1626<p><tt>dest</tt> is initialized to be equivalent to <tt>src</tt>,
1627potentially registering it with the runtime. Equivalent to the
1628following code:</p>
1629<pre>void objc_copyWeak(id *dest, id *src) {
1630 objc_release(objc_initWeak(dest, objc_loadWeakRetained(src)));
1631}</pre>
1632<p>Must be atomic with respect to calls to <tt>objc_storeWeak</tt>
1633on <tt>src</tt>.</p>
1634</div> <!-- runtime.objc_copyWeak -->
1635
1636<div id="runtime.objc_destroyWeak">
1637<h1><tt>void objc_destroyWeak(id *object);</tt></h1>
1638<p><i>Precondition:</i> <tt>object</tt> is a valid pointer which
1639either contains a null pointer or has been registered as
1640a <tt>__weak</tt> object.</p>
1641<p><tt>object</tt> is unregistered as a weak object, if it ever was.
1642The current value of <tt>object</tt> is left unspecified; otherwise,
1643equivalent to the following code:</p>
1644<pre>void objc_destroyWeak(id *object) {
1645 objc_storeWeak(object, nil);
1646}</pre>
1647<p>Does not need to be atomic with respect to calls
1648to <tt>objc_storeWeak</tt> on <tt>object</tt>.</p>
1649</div> <!-- runtime.objc_destroyWeak -->
1650
1651<div id="runtime.objc_initWeak">
1652<h1><tt>id objc_initWeak(id *object, id value);</tt></h1>
1653<p><i>Precondition:</i> <tt>object</tt> is a valid pointer which has
1654not been registered as a <tt>__weak</tt> object. <tt>value</tt> is
1655null or a pointer to a valid object.</p>
1656<p>If <tt>value</tt> is a null pointer or the object to which it
1657points has begun deallocation, <tt>object</tt> is zero-initialized.
1658Otherwise, <tt>object</tt> is registered as a <tt>__weak</tt> object
1659pointing to <tt>value</tt>. Equivalent to the following code:</p>
1660<pre>id objc_initWeak(id *object, id value) {
1661 *object = nil;
1662 return objc_storeWeak(object, value);
1663}</pre>
1664<p>Returns the value of <tt>object</tt> after the call.</p>
1665<p>Does not need to be atomic with respect to calls
1666to <tt>objc_storeWeak</tt> on <tt>object</tt>.</p>
1667</div> <!-- runtime.objc_initWeak -->
1668
1669<div id="runtime.objc_loadWeak">
1670<h1><tt>id objc_loadWeak(id *object);</tt></h1>
1671<p><i>Precondition:</i> <tt>object</tt> is a valid pointer which
1672either contains a null pointer or has been registered as
1673a <tt>__weak</tt> object.</p>
1674<p>If <tt>object</tt> is registered as a <tt>__weak</tt> object, and
1675the last value stored into <tt>object</tt> has not yet been
1676deallocated or begun deallocation, retains and autoreleases that value
1677and returns it. Otherwise returns null. Equivalent to the following
1678code:</p>
1679<pre>id objc_loadWeak(id *object) {
1680 return objc_autorelease(objc_loadWeakRetained(object));
1681}</pre>
1682<p>Must be atomic with respect to calls to <tt>objc_storeWeak</tt>
1683on <tt>object</tt>.</p>
1684<div class="rationale">Rationale: loading weak references would be
1685inherently prone to race conditions without the retain.</div>
1686</div> <!-- runtime.objc_loadWeak -->
1687
1688<div id="runtime.objc_loadWeakRetained">
1689<h1><tt>id objc_loadWeakRetained(id *object);</tt></h1>
1690<p><i>Precondition:</i> <tt>object</tt> is a valid pointer which
1691either contains a null pointer or has been registered as
1692a <tt>__weak</tt> object.</p>
1693<p>If <tt>object</tt> is registered as a <tt>__weak</tt> object, and
1694the last value stored into <tt>object</tt> has not yet been
1695deallocated or begun deallocation, retains that value and returns it.
1696Otherwise returns null.</p>
1697<p>Must be atomic with respect to calls to <tt>objc_storeWeak</tt>
1698on <tt>object</tt>.</p>
1699</div> <!-- runtime.objc_loadWeakRetained -->
1700
1701<div id="runtime.objc_moveWeak">
1702<h1><tt>void objc_moveWeak(id *dest, id *src);</tt></h1>
1703<p><i>Precondition:</i> <tt>src</tt> is a valid pointer which either
1704contains a null pointer or has been registered as a <tt>__weak</tt>
1705object. <tt>dest</tt> is a valid pointer which has not been
1706registered as a <tt>__weak</tt> object.</p>
1707<p><tt>dest</tt> is initialized to be equivalent to <tt>src</tt>,
1708potentially registering it with the runtime. <tt>src</tt> may then be
1709left in its original state, in which case this call is equivalent
1710to <a href="#runtime.objc_copyWeak"><tt>objc_copyWeak</tt></a>, or it
1711may be left as null.</p>
1712<p>Must be atomic with respect to calls to <tt>objc_storeWeak</tt>
1713on <tt>src</tt>.</p>
1714</div> <!-- runtime.objc_moveWeak -->
1715
John McCall085d09d2011-06-19 10:12:24 +00001716<div id="runtime.objc_release">
1717<h1><tt>void objc_release(id value);</tt></h1>
1718<p><i>Precondition:</i> <tt>value</tt> is null or a pointer to a
1719valid object.</p>
1720<p>If <tt>value</tt> is null, this call has no effect. Otherwise, it
1721performs a release operation exactly as if the object had been sent
1722the <tt>release</tt> message.</p>
1723</div> <!-- runtime.objc_release -->
1724
John McCall98a48cf2011-06-19 09:36:02 +00001725<div id="runtime.objc_retain">
1726<h1><tt>id objc_retain(id value);</tt></h1>
1727<p><i>Precondition:</i> <tt>value</tt> is null or a pointer to a
1728valid object.</p>
1729<p>If <tt>value</tt> is null, this call has no effect. Otherwise, it
1730performs a retain operation exactly as if the object had been sent
1731the <tt>retain</tt> message.</p>
1732<p>Always returns <tt>value</tt>.</p>
1733</div> <!-- runtime.objc_retain -->
1734
1735<div id="runtime.objc_retainAutorelease">
1736<h1><tt>id objc_retainAutorelease(id value);</tt></h1>
1737<p><i>Precondition:</i> <tt>value</tt> is null or a pointer to a
1738valid object.</p>
1739<p>If <tt>value</tt> is null, this call has no effect. Otherwise, it
1740performs a retain operation followed by an autorelease operation.
1741Equivalent to the following code:</p>
1742<pre>id objc_retainAutorelease(id value) {
1743 return objc_autorelease(objc_retain(value));
1744}</pre>
1745<p>Always returns <tt>value</tt>.</p>
1746</div> <!-- runtime.objc_retainAutorelease -->
1747
1748<div id="runtime.objc_retainAutoreleaseReturnValue">
1749<h1><tt>id objc_retainAutoreleaseReturnValue(id value);</tt></h1>
1750<p><i>Precondition:</i> <tt>value</tt> is null or a pointer to a
1751valid object.</p>
1752<p>If <tt>value</tt> is null, this call has no effect. Otherwise, it
1753performs a retain operation followed by the operation described in
1754<a href="#runtime.objc_autoreleaseReturnValue"><tt>objc_autoreleaseReturnValue</tt></a>.
1755Equivalent to the following code:</p>
1756<pre>id objc_retainAutoreleaseReturnValue(id value) {
1757 return objc_autoreleaseReturnValue(objc_retain(value));
1758}</pre>
1759<p>Always returns <tt>value</tt>.</p>
1760</div> <!-- runtime.objc_retainAutoreleaseReturnValue -->
1761
1762<div id="runtime.objc_retainAutoreleasedReturnValue">
1763<h1><tt>id objc_retainAutoreleasedReturnValue(id value);</tt></h1>
1764<p><i>Precondition:</i> <tt>value</tt> is null or a pointer to a
1765valid object.</p>
1766<p>If <tt>value</tt> is null, this call has no effect. Otherwise, it
1767attempts to accept a hand off of a retain count from a call to
1768<a href="#runtime.objc_autoreleaseReturnValue"><tt>objc_autoreleaseReturnValue</tt></a>
1769on <tt>value</tt> in a recently-called function or something it
1770calls. If that fails, it performs a retain operation exactly
1771like <a href="#runtime.objc_retain"><tt>objc_retain</tt></a>.</p>
1772<p>Always returns <tt>value</tt>.</p>
1773</div> <!-- runtime.objc_retainAutoreleasedReturnValue -->
1774
1775<div id="runtime.objc_retainBlock">
1776<h1><tt>id objc_retainBlock(id value);</tt></h1>
1777<p><i>Precondition:</i> <tt>value</tt> is null or a pointer to a
1778valid block object.</p>
1779<p>If <tt>value</tt> is null, this call has no effect. Otherwise, if
1780the block pointed to by <tt>value</tt> is still on the stack, it is
1781copied to the heap and the address of the copy is returned. Otherwise
1782a retain operation is performed on the block exactly as if it had been
1783sent the <tt>retain</tt> message.</p>
1784</div> <!-- runtime.objc_retainBlock -->
1785
John McCall98a48cf2011-06-19 09:36:02 +00001786<div id="runtime.objc_storeStrong">
1787<h1><tt>id objc_storeStrong(id *object, id value);</tt></h1>
1788<p><i>Precondition:</i> <tt>object</tt> is a valid pointer to
1789a <tt>__strong</tt> object which is adequately aligned for a
1790pointer. <tt>value</tt> is null or a pointer to a valid object.</p>
1791<p>Performs the complete sequence for assigning to a <tt>__strong</tt>
1792object of non-block type. Equivalent to the following code:</p>
1793<pre>id objc_storeStrong(id *object, id value) {
1794 value = [value retain];
1795 id oldValue = *object;
1796 *object = value;
1797 [oldValue release];
1798 return value;
1799}</pre>
1800<p>Always returns <tt>value</tt>.</p>
1801</div> <!-- runtime.objc_storeStrong -->
1802
1803<div id="runtime.objc_storeWeak">
1804<h1><tt>id objc_storeWeak(id *object, id value);</tt></h1>
1805<p><i>Precondition:</i> <tt>object</tt> is a valid pointer which
1806either contains a null pointer or has been registered as
1807a <tt>__weak</tt> object. <tt>value</tt> is null or a pointer to a
1808valid object.</p>
1809<p>If <tt>value</tt> is a null pointer or the object to which it
1810points has begun deallocation, <tt>object</tt> is assigned null
1811and unregistered as a <tt>__weak</tt> object. Otherwise,
1812<tt>object</tt> is registered as a <tt>__weak</tt> object or has its
1813registration updated to point to <tt>value</tt>.</p>
1814<p>Returns the value of <tt>object</tt> after the call.</p>
1815</div> <!-- runtime.objc_storeWeak -->
1816
1817</div> <!-- runtime -->
John McCall82467022011-06-15 21:21:53 +00001818</div> <!-- root -->
1819</body>
1820</html>