Home | History | Annotate | Download | only in docs
      1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
      2           "http://www.w3.org/TR/html4/strict.dtd">
      3 <html>
      4 <head>
      5 <title>Objective-C Automatic Reference Counting (ARC)</title>
      6 <link type="text/css" rel="stylesheet" href="../menu.css">
      7 <link type="text/css" rel="stylesheet" href="../content.css">
      8 <style type="text/css">
      9 /* Collapse the items in the ToC to the left. */
     10 div#toc ul {
     11   padding-left: 0
     12 }
     13 
     14 /* Rationales appear in italic. */
     15 div.rationale {
     16   font-style: italic
     17 }
     18 
     19 div.rationale em {
     20   font-style: normal
     21 }
     22 
     23 /* Revisions are also italicized. */
     24 span.revision {
     25   font-style: italic
     26 }
     27 
     28 span.whenRevised {
     29   font-weight: bold;
     30   font-style: normal
     31 }
     32 
     33 div h1 { font-size: 2em; margin: .67em 0 }
     34 div div h1 { font-size: 1.5em; margin: .75em 0 }
     35 div div div h1 { font-size: 1.17em; margin: .83em 0 }
     36 div div div div h1 { margin: 1.12em 0 }
     37 
     38 span.term { font-style: italic; font-weight: bold  }
     39 </style>
     40 
     41 <script type="text/javascript">
     42 /// A little script to recursively build a table of contents.
     43 function buildTOC(div, toc, ancestry) {
     44   var children = div.childNodes;
     45   var len = children.length;
     46 
     47   var childNumber = 0;
     48 
     49   var list = null;
     50   for (var i = 0; i < len; ++i) {
     51     var child = children[i];
     52     if (child.nodeName != "DIV") continue;
     53     if (child.getAttribute("class") == "rationale") continue;
     54     if (child.id == "toc") continue;
     55 
     56     // Okay, we're actually going to build a list node.
     57     if (list === null) list = document.createElement("ul");
     58 
     59     var childAncestry = ancestry + ++childNumber + ".";
     60 
     61     var headerNode = child.childNodes[1];
     62     var title = headerNode.innerHTML;
     63     headerNode.insertBefore(document.createTextNode(childAncestry + " "),
     64                             headerNode.firstChild);
     65 
     66     var item = document.createElement("li");
     67     item.appendChild(document.createTextNode(childAncestry + " "));
     68 
     69     var anchor = document.createElement("a");
     70     anchor.href = "#" + child.id;
     71     anchor.innerHTML = title;
     72     item.appendChild(anchor);
     73 
     74     buildTOC(child, item, childAncestry);
     75 
     76     list.appendChild(item);
     77   }
     78   if (list) toc.appendChild(list);
     79 }
     80 
     81 function onLoad() {
     82   var toc = document.getElementById("toc");
     83   var content = document.getElementById("content");
     84   buildTOC(content, toc, "");
     85 }
     86 window.onload = onLoad;
     87 
     88 
     89 
     90 
     91 
     92 
     93 
     94 
95

Automatic Reference Counting

96 97 99 100
101

About this document

102 103
meta.purpose"> 104

Purpose

105 106

The first and primary purpose of this document is to serve as a 107 complete technical specification of Automatic Reference Counting. 108 Given a core Objective-C compiler and runtime, it should be possible 109 to write a compiler and runtime which implements these new 110 semantics.

111 112

The secondary purpose is to act as a rationale for why ARC was 113 designed in this way. This should remain tightly focused on the 114 technical design and should not stray into marketing speculation.

115 116
117 118
meta.background"> 119

Background

120 121

This document assumes a basic familiarity with C.

122 123

Blocks are a C language extension for 124 creating anonymous functions. Users interact with and transfer block 125 objects using block pointers, which are 126 represented like a normal pointer. A block may capture values from 127 local variables; when this occurs, memory must be dynamically 128 allocated. The initial allocation is done on the stack, but the 129 runtime provides a Block_copy function which, given a block 130 pointer, either copies the underlying block object to the heap, 131 setting its reference count to 1 and returning the new block pointer, 132 or (if the block object is already on the heap) increases its 133 reference count by 1. The paired function is Block_release, 134 which decreases the reference count by 1 and destroys the object if 135 the count reaches zero and is on the heap.

136 137

Objective-C is a set of language extensions, significant enough to 138 be considered a different language. It is a strict superset of C. 139 The extensions can also be imposed on C++, producing a language called 140 Objective-C++. The primary feature is a single-inheritance object 141 system; we briefly describe the modern dialect.

142 143

Objective-C defines a new type kind, collectively called 144 the object pointer types. This kind has two 145 notable builtin members, id and Class; id 146 is the final supertype of all object pointers. The validity of 147 conversions between object pointer types is not checked at runtime. 148 Users may define classes; each class is a 149 type, and the pointer to that type is an object pointer type. A class 150 may have a superclass; its pointer type is a subtype of its 151 superclass's pointer type. A class has a set 152 of <span class="term">ivars</span>, fields which appear on all 153 instances of that class. For every class <i>T</i> there's an 154 associated metaclass; it has no fields, its superclass is the 155 metaclass of <i>T</i>'s superclass, and its metaclass is a global 156 class. Every class has a global object whose class is the 157 class's metaclass; metaclasses have no associated type, so pointers to 158 this object have type <tt>Class</tt>.</p> 159 160 <p>A class declaration (<tt>@interface</tt>) declares a set 161 of <span class="term">methods</span>. A method has a return type, a 162 list of argument types, and a <span class="term">selector</span>: a 163 name like <tt>foo:bar:baz:</tt>, where the number of colons 164 corresponds to the number of formal arguments. A method may be an 165 instance method, in which case it can be invoked on objects of the 166 class, or a class method, in which case it can be invoked on objects 167 of the metaclass. A method may be invoked by providing an object 168 (called the <span class="term">receiver</span>) and a list of formal 169 arguments interspersed with the selector, like so:</p> 170 171 <pre>[receiver foo: fooArg bar: barArg baz: bazArg]</pre> 172 173 <p>This looks in the dynamic class of the receiver for a method with 174 this name, then in that class's superclass, etc., until it finds 175 something it can execute. The receiver <q>expression</q> may also be 176 the name of a class, in which case the actual receiver is the class 177 object for that class, or (within method definitions) it may 178 be <tt>super</tt>, in which case the lookup algorithm starts with the 179 static superclass instead of the dynamic class. The actual methods 180 dynamically found in a class are not those declared in the 181 <tt>@interface</tt>, but those defined in a separate 182 <tt>@implementation</tt> declaration; however, when compiling a 183 call, typechecking is done based on the methods declared in the 184 <tt>@interface</tt>.</p> 185 186 <p>Method declarations may also be grouped into 187 <span class="term">protocols</span>, which are not inherently 188 associated with any class, but which classes may claim to follow. 189 Object pointer types may be qualified with additional protocols that 190 the object is known to support.</p> 191 192 <p><span class="term">Class extensions</span> are collections of ivars 193 and methods, designed to allow a class's <tt>@interface</tt> to be 194 split across multiple files; however, there is still a primary 195 implementation file which must see the <tt>@interface</tt>s of all 196 class extensions. 197 <span class="term">Categories</span> allow methods (but not ivars) to 198 be declared <i>post hoc</i> on an arbitrary class; the methods in the 199 category's <tt>@implementation</tt> will be dynamically added to that 200 class's method tables which the category is loaded at runtime, 201 replacing those methods in case of a collision.</p> 202 203 <p>In the standard environment, objects are allocated on the heap, and 204 their lifetime is manually managed using a reference count. This is 205 done using two instance methods which all classes are expected to 206 implement: <tt>retain</tt> increases the object's reference count by 207 1, whereas <tt>release</tt> decreases it by 1 and calls the instance 208 method <tt>dealloc</tt> if the count reaches 0. To simplify certain 209 operations, there is also an <span class="term">autorelease 210 pool</span>, a thread-local list of objects to call <tt>release</tt> 211 on later; an object can be added to this pool by 212 calling <tt>autorelease</tt> on it.</p> 213 214 <p>Block pointers may be converted to type <tt>id</tt>; block objects 215 are laid out in a way that makes them compatible with Objective-C 216 objects. There is a builtin class that all block objects are 217 considered to be objects of; this class implements <tt>retain</tt> by 218 adjusting the reference count, not by calling <tt>Block_copy</tt>.</p> 219 220 </div> <!-- meta.background --> 221 222 <div id="meta.evolution"> 223 <h1>Evolution</h1> 224 225 <p>ARC is under continual evolution, and this document must be updated 226 as the language progresses.</p> 227 228 <p>If a change increases the expressiveness of the language, for 229 example by lifting a restriction or by adding new syntax, the change 230 will be annotated with a revision marker, like so:</p> 231 232 <blockquote> 233 ARC applies to Objective-C pointer types, block pointer types, and 234 <span class="revision"><span class="whenRevised">[beginning Apple 235 8.0, LLVM 3.8]</span> BPTRs declared within <code>extern 236 "BCPL"</code> blocks</span>. 237 </blockquote> 238 239 <p>For now, it is sensible to version this document by the releases of 240 its sole implementation (and its host project), clang. 241 <q>LLVM X.Y</q> refers to an open-source release of clang from the 242 LLVM project. <q>Apple X.Y</q> refers to an Apple-provided release of 243 the Apple LLVM Compiler. Other organizations that prepare their own, 244 separately-versioned clang releases and wish to maintain similar 245 information in this document should send requests to cfe-dev.</p> 246 247 <p>If a change decreases the expressiveness of the language, for 248 example by imposing a new restriction, this should be taken as an 249 oversight in the original specification and something to be avoided 250 in all versions. Such changes are generally to be avoided.</p> 251 252 </div> <!-- meta.evolution --> 253 254 </div> <!-- meta --> 255 256 <div id="general"> 257 <h1>General</h1> 258 259 <p>Automatic Reference Counting implements automatic memory management 260 for Objective-C objects and blocks, freeing the programmer from the 261 need to explicitly insert retains and releases. It does not provide a 262 cycle collector; users must explicitly manage the lifetime of their 263 objects, breaking cycles manually or with weak or unsafe 264 references.</p> 265 266 <p>ARC may be explicitly enabled with the compiler 267 flag <tt>-fobjc-arc</tt>. It may also be explicitly disabled with the 268 compiler flag <tt>-fno-objc-arc</tt>. The last of these two flags 269 appearing on the compile line <q>wins</q>.</p> 270 271 <p>If ARC is enabled, <tt>__has_feature(objc_arc)</tt> will expand to 272 1 in the preprocessor. For more information about <tt>__has_feature</tt>, 273 see the <a href="LanguageExtensions.html#__has_feature_extension">language 274 extensions</a> document.</p> 275 276 </div> <!-- general --> 277 278 <div id="objects"> 279 <h1>Retainable object pointers</h1> 280 281 <p>This section describes retainable object pointers, their basic 282 operations, and the restrictions imposed on their use under ARC. Note 283 in particular that it covers the rules for pointer <em>values</em> 284 (patterns of bits indicating the location of a pointed-to object), not 285 pointer 286 <em>objects</em> (locations in memory which store pointer values). 287 The rules for objects are covered in the next section.</p> 288 289 <p>A <span class="term">retainable object pointer</span> 290 (or <q>retainable pointer</q>) is a value of 291 a <span class="term">retainable object pointer type</span> 292 (<q>retainable type</q>). There are three kinds of retainable object 293 pointer types:</p> 294 <ul> 295 <li>block pointers (formed by applying the caret (<tt>^</tt>) 296 declarator sigil to a function type)</li> 297 <li>Objective-C object pointers (<tt>id</tt>, <tt>Class</tt>, <tt>NSFoo*</tt>, etc.)</li> 298 <li>typedefs marked with <tt>__attribute__((NSObject))</tt></li> 299 </ul> 300 301 <p>Other pointer types, such as <tt>int*</tt> and <tt>CFStringRef</tt>, 302 are not subject to ARC's semantics and restrictions.</p> 303 304 <div class="rationale"> 305 306 <p>Rationale: We are not at liberty to require 307 all code to be recompiled with ARC; therefore, ARC must interoperate 308 with Objective-C code which manages retains and releases manually. In 309 general, there are three requirements in order for a 310 compiler-supported reference-count system to provide reliable 311 interoperation:</p> 312 313 <ul> 314 <li>The type system must reliably identify which objects are to be 315 managed. An <tt>int*</tt> might be a pointer to a <tt>malloc</tt>'ed 316 array, or it might be an interior pointer to such an array, or it might 317 point to some field or local variable. In contrast, values of the 318 retainable object pointer types are never interior.</li> 319 <li>The type system must reliably indicate how to 320 manage objects of a type. This usually means that the type must imply 321 a procedure for incrementing and decrementing retain counts. 322 Supporting single-ownership objects requires a lot more explicit 323 mediation in the language.</li> 324 <li>There must be reliable conventions for whether and 325 when <q>ownership</q> is passed between caller and callee, for both 326 arguments and return values. Objective-C methods follow such a 327 convention very reliably, at least for system libraries on Mac OS X, 328 and functions always pass objects at +0. The C-based APIs for Core 329 Foundation objects, on the other hand, have much more varied transfer 330 semantics.</li> 331 </ul> 332 </div> <!-- rationale --> 333 334 <p>The use of <tt>__attribute__((NSObject))</tt> typedefs is not 335 recommended. If it's absolutely necessary to use this attribute, be 336 very explicit about using the typedef, and do not assume that it will 337 be preserved by language features like <tt>__typeof</tt> and C++ 338 template argument substitution.</p> 339 340 <div class="rationale"><p>Rationale: any compiler operation which 341 incidentally strips type <q>sugar</q> from a type will yield a type 342 without the attribute, which may result in unexpected 343 behavior.</p></div> 344 345 <div id="objects.retains"> 346 <h1>Retain count semantics</h1> 347 348 <p>A retainable object pointer is either a <span class="term">null 349 pointer</span> or a pointer to a valid object. Furthermore, if it has 350 block pointer type and is not <tt>null</tt> then it must actually be a 351 pointer to a block object, and if it has <tt>Class</tt> type (possibly 352 protocol-qualified) then it must actually be a pointer to a class 353 object. Otherwise ARC does not enforce the Objective-C type system as 354 long as the implementing methods follow the signature of the static 355 type. It is undefined behavior if ARC is exposed to an invalid 356 pointer.</p> 357 358 <p>For ARC's purposes, a valid object is one with <q>well-behaved</q> 359 retaining operations. Specifically, the object must be laid out such 360 that the Objective-C message send machinery can successfully send it 361 the following messages:</p> 362 363 <ul> 364 <li><tt>retain</tt>, taking no arguments and returning a pointer to 365 the object.</li> 366 <li><tt>release</tt>, taking no arguments and returning <tt>void</tt>.</li> 367 <li><tt>autorelease</tt>, taking no arguments and returning a pointer 368 to the object.</li> 369 </ul> 370 371 <p>The behavior of these methods is constrained in the following ways. 372 The term <span class="term">high-level semantics</span> is an 373 intentionally vague term; the intent is that programmers must 374 implement these methods in a way such that the compiler, modifying 375 code in ways it deems safe according to these constraints, will not 376 violate their requirements. For example, if the user puts logging 377 statements in <tt>retain</tt>, they should not be surprised if those 378 statements are executed more or less often depending on optimization 379 settings. These constraints are not exhaustive of the optimization 380 opportunities: values held in local variables are subject to 381 additional restrictions, described later in this document.</p> 382 383 <p>It is undefined behavior if a computation history featuring a send 384 of <tt>retain</tt> followed by a send of <tt>release</tt> to the same 385 object, with no intervening <tt>release</tt> on that object, is not 386 equivalent under the high-level semantics to a computation 387 history in which these sends are removed. Note that this implies that 388 these methods may not raise exceptions.</p> 389 390 <p>It is undefined behavior if a computation history features any use 391 whatsoever of an object following the completion of a send 392 of <tt>release</tt> that is not preceded by a send of <tt>retain</tt> 393 to the same object.</p> 394 395 <p>The behavior of <tt>autorelease</tt> must be equivalent to sending 396 <tt>release</tt> when one of the autorelease pools currently in scope 397 is popped. It may not throw an exception.</p> 398 399 <p>When the semantics call for performing one of these operations on a 400 retainable object pointer, if that pointer is <tt>null</tt> then the 401 effect is a no-op.</p> 402 403 <p>All of the semantics described in this document are subject to 404 additional <a href="#optimization">optimization rules</a> which permit 405 the removal or optimization of operations based on local knowledge of 406 data flow. The semantics describe the high-level behaviors that the 407 compiler implements, not an exact sequence of operations that a 408 program will be compiled into.</p> 409 410 </div> <!-- objects.retains --> 411 412 <div id="objects.operands"> 413 <h1>Retainable object pointers as operands and arguments</h1> 414 415 <p>In general, ARC does not perform retain or release operations when 416 simply using a retainable object pointer as an operand within an 417 expression. This includes:</p> 418 <ul> 419 <li>loading a retainable pointer from an object with non-weak 420 <a href="#ownership">ownership</a>,</li> 421 <li>passing a retainable pointer as an argument to a function or 422 method, and</li> 423 <li>receiving a retainable pointer as the result of a function or 424 method call.</li> 425 </ul> 426 427 <div class="rationale"><p>Rationale: while this might seem 428 uncontroversial, it is actually unsafe when multiple expressions are 429 evaluated in <q>parallel</q>, as with binary operators and calls, 430 because (for example) one expression might load from an object while 431 another writes to it. However, C and C++ already call this undefined 432 behavior because the evaluations are unsequenced, and ARC simply 433 exploits that here to avoid needing to retain arguments across a large 434 number of calls.</p></div> 435 436 <p>The remainder of this section describes exceptions to these rules, 437 how those exceptions are detected, and what those exceptions imply 438 semantically.</p> 439 440 <div id="objects.operands.consumed"> 441 <h1>Consumed parameters</h1> 442 443 <p>A function or method parameter of retainable object pointer type 444 may be marked as <span class="term">consumed</span>, signifying that 445 the callee expects to take ownership of a +1 retain count. This is 446 done by adding the <tt>ns_consumed</tt> attribute to the parameter 447 declaration, like so:</p> 448 449 <pre>void foo(__attribute((ns_consumed)) id x); 450 - (void) foo: (id) __attribute((ns_consumed)) x;</pre> 451 452 <p>This attribute is part of the type of the function or method, not 453 the type of the parameter. It controls only how the argument is 454 passed and received.</p> 455 456 <p>When passing such an argument, ARC retains the argument prior to 457 making the call.</p> 458 459 <p>When receiving such an argument, ARC releases the argument at the 460 end of the function, subject to the usual optimizations for local 461 values.</p> 462 463 <div class="rationale"><p>Rationale: this formalizes direct transfers 464 of ownership from a caller to a callee. The most common scenario here 465 is passing the <tt>self</tt> parameter to <tt>init</tt>, but it is 466 useful to generalize. Typically, local optimization will remove any 467 extra retains and releases: on the caller side the retain will be 468 merged with a +1 source, and on the callee side the release will be 469 rolled into the initialization of the parameter.</p></div> 470 471 <p>The implicit <tt>self</tt> parameter of a method may be marked as 472 consumed by adding <tt>__attribute__((ns_consumes_self))</tt> to the 473 method declaration. Methods in the <tt>init</tt> 474 <a href="#family">family</a> are treated as if they were implicitly 475 marked with this attribute.</p> 476 477 <p>It is undefined behavior if an Objective-C message send to a method 478 with <tt>ns_consumed</tt> parameters (other than self) is made with a 479 null receiver. It is undefined behavior if the method to which an 480 Objective-C message send statically resolves to has a different set 481 of <tt>ns_consumed</tt> parameters than the method it dynamically 482 resolves to. It is undefined behavior if a block or function call is 483 made through a static type with a different set of <tt>ns_consumed</tt> 484 parameters than the implementation of the called block or function.</p> 485 486 <div class="rationale"><p>Rationale: consumed parameters with null 487 receiver are a guaranteed leak. Mismatches with consumed parameters 488 will cause over-retains or over-releases, depending on the direction. 489 The rule about function calls is really just an application of the 490 existing C/C++ rule about calling functions through an incompatible 491 function type, but it's useful to state it explicitly.</p></div> 492 493 </div> <!-- objects.operands.consumed --> 494 495 <div id="objects.operands.retained-returns"> 496 <h1>Retained return values</h1> 497 498 <p>A function or method which returns a retainable object pointer type 499 may be marked as returning a retained value, signifying that the 500 caller expects to take ownership of a +1 retain count. This is done 501 by adding the <tt>ns_returns_retained</tt> attribute to the function or 502 method declaration, like so:</p> 503 504 <pre>id foo(void) __attribute((ns_returns_retained)); 505 - (id) foo __attribute((ns_returns_retained));</pre> 506 507 <p>This attribute is part of the type of the function or method.</p> 508 509 <p>When returning from such a function or method, ARC retains the 510 value at the point of evaluation of the return statement, before 511 leaving all local scopes.</p> 512 513 <p>When receiving a return result from such a function or method, ARC 514 releases the value at the end of the full-expression it is contained 515 within, subject to the usual optimizations for local values.</p> 516 517 <div class="rationale"><p>Rationale: this formalizes direct transfers of 518 ownership from a callee to a caller. The most common scenario this 519 models is the retained return from <tt>init</tt>, <tt>alloc</tt>, 520 <tt>new</tt>, and <tt>copy</tt> methods, but there are other cases in 521 the frameworks. After optimization there are typically no extra 522 retains and releases required.</p></div> 523 524 <p>Methods in 525 the <tt>alloc</tt>, <tt>copy</tt>, <tt>init</tt>, <tt>mutableCopy</tt>, 526 and <tt>new</tt> <a href="#family">families</a> are implicitly marked 527 <tt>__attribute__((ns_returns_retained))</tt>. This may be suppressed 528 by explicitly marking the 529 method <tt>__attribute__((ns_returns_not_retained))</tt>.</p> 530 531 <p>It is undefined behavior if the method to which an Objective-C 532 message send statically resolves has different retain semantics on its 533 result from the method it dynamically resolves to. It is undefined 534 behavior if a block or function call is made through a static type 535 with different retain semantics on its result from the implementation 536 of the called block or function.</p> 537 538 <div class="rationale"><p>Rationale: Mismatches with returned results 539 will cause over-retains or over-releases, depending on the direction. 540 Again, the rule about function calls is really just an application of 541 the existing C/C++ rule about calling functions through an 542 incompatible function type.</p></div> 543 544 </div> <!-- objects.operands.retained-returns --> 545 546 <div id="objects.operands.other-returns"> 547 <h1>Unretained return values</h1> 548 549 <p>A method or function which returns a retainable object type but 550 does not return a retained value must ensure that the object is 551 still valid across the return boundary.</p> 552 553 <p>When returning from such a function or method, ARC retains the 554 value at the point of evaluation of the return statement, then leaves 555 all local scopes, and then balances out the retain while ensuring that 556 the value lives across the call boundary. In the worst case, this may 557 involve an <tt>autorelease</tt>, but callers must not assume that the 558 value is actually in the autorelease pool.</p> 559 560 <p>ARC performs no extra mandatory work on the caller side, although 561 it may elect to do something to shorten the lifetime of the returned 562 value.</p> 563 564 <div class="rationale"><p>Rationale: it is common in non-ARC code to not 565 return an autoreleased value; therefore the convention does not force 566 either path. It is convenient to not be required to do unnecessary 567 retains and autoreleases; this permits optimizations such as eliding 568 retain/autoreleases when it can be shown that the original pointer 569 will still be valid at the point of return.</p></div> 570 571 <p>A method or function may be marked 572 with <tt>__attribute__((ns_returns_autoreleased))</tt> to indicate 573 that it returns a pointer which is guaranteed to be valid at least as 574 long as the innermost autorelease pool. There are no additional 575 semantics enforced in the definition of such a method; it merely 576 enables optimizations in callers.</p> 577 578 </div> <!-- objects.operands.other-returns --> 579 580 <div id="objects.operands.casts"> 581 <h1>Bridged casts</h1> 582 583 <p>A <span class="term">bridged cast</span> is a C-style cast 584 annotated with one of three keywords:</p> 585 586 <ul> 587 <li><tt>(__bridge T) op</tt> casts the operand to the destination 588 type <tt>T</tt>. If <tt>T</tt> is a retainable object pointer type, 589 then <tt>op</tt> must have a non-retainable pointer type. 590 If <tt>T</tt> is a non-retainable pointer type, then <tt>op</tt> must 591 have a retainable object pointer type. Otherwise the cast is 592 ill-formed. There is no transfer of ownership, and ARC inserts 593 no retain operations.</li> 594 595 <li><tt>(__bridge_retained T) op</tt> casts the operand, which must 596 have retainable object pointer type, to the destination type, which 597 must be a non-retainable pointer type. ARC retains the value, subject 598 to the usual optimizations on local values, and the recipient is 599 responsible for balancing that +1.</li> 600 601 <li><tt>(__bridge_transfer T) op</tt> casts the operand, which must 602 have non-retainable pointer type, to the destination type, which must 603 be a retainable object pointer type. ARC will release the value at 604 the end of the enclosing full-expression, subject to the usual 605 optimizations on local values.</li> 606 </ul> 607 608 <p>These casts are required in order to transfer objects in and out of 609 ARC control; see the rationale in the section 610 on <a href="#objects.restrictions.conversion">conversion of retainable 611 object pointers</a>.</p> 612 613 <p>Using a <tt>__bridge_retained</tt> or <tt>__bridge_transfer</tt> 614 cast purely to convince ARC to emit an unbalanced retain or release, 615 respectively, is poor form.</p> 616 617 </div> <!-- objects.operands.casts --> 618 619 </div> <!-- objects.operands --> 620 621 <div id="objects.restrictions"> 622 <h1>Restrictions</h1> 623 624 <div id="objects.restrictions.conversion"> 625 <h1>Conversion of retainable object pointers</h1> 626 627 <p>In general, a program which attempts to implicitly or explicitly 628 convert a value of retainable object pointer type to any 629 non-retainable type, or vice-versa, is ill-formed. For example, an 630 Objective-C object pointer shall not be converted to <tt>void*</tt>. 631 As an exception, cast to <tt>intptr_t</tt> is allowed because such 632 casts are not transferring ownership. The <a href="#objects.operands.casts">bridged 633 casts</a> may be used to perform these conversions where 634 necessary.</p> 635 636 <div class="rationale"><p>Rationale: we cannot ensure the correct 637 management of the lifetime of objects if they may be freely passed 638 around as unmanaged types. The bridged casts are provided so that the 639 programmer may explicitly describe whether the cast transfers control 640 into or out of ARC.</p></div> 641 642 <p>However, the following exceptions apply.</p> 643 644 </div> <!-- objects.restrictions.conversion --> 645 646 <div id="objects.restrictions.conversion-exception-known"> 647 <h1>Conversion to retainable object pointer type of 648 expressions with known semantics</h1> 649 650 <p><span class="revision"><span class="whenRevised">[beginning Apple 651 4.0, LLVM 3.1]</span> These exceptions have been greatly expanded; 652 they previously applied only to a much-reduced subset which is 653 difficult to categorize but which included null pointers, message 654 sends (under the given rules), and the various global constants.</span></p> 655 656 <p>An unbridged conversion to a retainable object pointer type from a 657 type other than a retainable object pointer type is ill-formed, as 658 discussed above, unless the operand of the cast has a syntactic form 659 which is known retained, known unretained, or known 660 retain-agnostic.</p> 661 662 <p>An expression is <span class="term">known retain-agnostic</span> if 663 it is:</p> 664 <ul> 665 <li>an Objective-C string literal,</li> 666 <li>a load from a <tt>const</tt> system global variable of 667 <a href="#misc.c-retainable">C retainable pointer type</a>, or</li> 668 <li>a null pointer constant.</li> 669 </ul> 670 671 <p>An expression is <span class="term">known unretained</span> if it 672 is an rvalue of <a href="#misc.c-retainable">C retainable 673 pointer type</a> and it is:</p> 674 <ul> 675 <li>a direct call to a function, and either that function has the 676 <tt>cf_returns_not_retained</tt> attribute or it is an 677 <a href="#misc.c-retainable.audit">audited</a> function that does not 678 have the <tt>cf_returns_retained</tt> attribute and does not follow 679 the create/copy naming convention,</li> 680 <li>a message send, and the declared method either has 681 the <tt>cf_returns_not_retained</tt> attribute or it has neither 682 the <tt>cf_returns_retained</tt> attribute nor a 683 <a href="#family">selector family</a> that implies a retained 684 result.</li> 685 </ul> 686 687 <p>An expression is <span class="term">known retained</span> if it is 688 an rvalue of <a href="#misc.c-retainable">C retainable pointer type</a> 689 and it is:</p> 690 <ul> 691 <li>a message send, and the declared method either has the 692 <tt>cf_returns_retained</tt> attribute, or it does not have 693 the <tt>cf_returns_not_retained</tt> attribute but it does have a 694 <a href="#family">selector family</a> that implies a retained 695 result.</li> 696 </ul> 697 698 <p>Furthermore:</p> 699 <ul> 700 <li>a comma expression is classified according to its right-hand side,</li> 701 <li>a statement expression is classified according to its result 702 expression, if it has one,</li> 703 <li>an lvalue-to-rvalue conversion applied to an Objective-C property 704 lvalue is classified according to the underlying message send, and</li> 705 <li>a conditional operator is classified according to its second and 706 third operands, if they agree in classification, or else the other 707 if one is known retain-agnostic.</li> 708 </ul> 709 710 <p>If the cast operand is known retained, the conversion is treated as 711 a <tt>__bridge_transfer</tt> cast. If the cast operand is known 712 unretained or known retain-agnostic, the conversion is treated as 713 a <tt>__bridge</tt> cast.</p> 714 715 <div class="rationale"><p>Rationale: Bridging casts are annoying. 716 Absent the ability to completely automate the management of CF 717 objects, however, we are left with relatively poor attempts to reduce 718 the need for a glut of explicit bridges. Hence these rules.</p> 719 720 <p>We've so far consciously refrained from implicitly turning retained 721 CF results from function calls into <tt>__bridge_transfer</tt> casts. 722 The worry is that some code patterns &mdash; for example, creating a 723 CF value, assigning it to an ObjC-typed local, and then 724 calling <tt>CFRelease</tt> when done &mdash; are a bit too likely to 725 be accidentally accepted, leading to mysterious behavior.</p></div> 726 727 </div> <!-- objects.restrictions.conversion-exception-known --> 728 729 <div id="objects.restrictions.conversion-exception-contextual"> 730 <h1>Conversion from retainable object pointer type in certain contexts</h1> 731 732 <p><span class="revision"><span class="whenRevised">[beginning Apple 733 4.0, LLVM 3.1]</span></span></p> 734 735 <p>If an expression of retainable object pointer type is explicitly 736 cast to a <a href="#misc.c-retainable">C retainable pointer type</a>, 737 the program is ill-formed as discussed above unless the result is 738 immediately used:</p> 739 740 <ul> 741 <li>to initialize a parameter in an Objective-C message send where the 742 parameter is not marked with the <tt>cf_consumed</tt> attribute, or</li> 743 <li>to initialize a parameter in a direct call to 744 an <a href="#misc.c-retainable.audit">audited</a> function where the 745 parameter is not marked with the <tt>cf_consumed</tt> attribute.</li> 746 </ul> 747 748 <div class="rationale"><p>Rationale: Consumed parameters are left out 749 because ARC would naturally balance them with a retain, which was 750 judged too treacherous. This is in part because several of the most 751 common consuming functions are in the <tt>Release</tt> family, and it 752 would be quite unfortunate for explicit releases to be silently 753 balanced out in this way.</p></div> 754 755 </div> <!-- objects.restrictions.conversion-exception-contextual --> 756 757 </div> <!-- objects.restrictions --> 758 759 </div> <!-- objects --> 760 761 <div id="ownership"> 762 <h1>Ownership qualification</h1> 763 764 <p>This section describes the behavior of <em>objects</em> of 765 retainable object pointer type; that is, locations in memory which 766 store retainable object pointers.</p> 767 768 <p>A type is a <span class="term">retainable object owner type</span> 769 if it is a retainable object pointer type or an array type whose 770 element type is a retainable object owner type.</p> 771 772 <p>An <span class="term">ownership qualifier</span> is a type 773 qualifier which applies only to retainable object owner types. An array type is 774 ownership-qualified according to its element type, and adding an ownership 775 qualifier to an array type so qualifies its element type.</p> 776 777 <p>A program is ill-formed if it attempts to apply an ownership qualifier 778 to a type which is already ownership-qualified, even if it is the same 779 qualifier. There is a single exception to this rule: an ownership qualifier 780 may be applied to a substituted template type parameter, which overrides the 781 ownership qualifier provided by the template argument.</p> 782 783 <p>Except as described under 784 the <a href="#ownership.inference">inference rules</a>, a program is 785 ill-formed if it attempts to form a pointer or reference type to a 786 retainable object owner type which lacks an ownership qualifier.</p> 787 788 <div class="rationale"><p>Rationale: these rules, together with the 789 inference rules, ensure that all objects and lvalues of retainable 790 object 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> 791 792 <p>There are four ownership qualifiers:</p> 793 794 <ul> 795 <li><tt>__autoreleasing</tt></li> 796 <li><tt>__strong</tt></li> 797 <li><tt>__unsafe_unretained</tt></li> 798 <li><tt>__weak</tt></li> 799 </ul> 800 801 <p>A type is <span class="term">nontrivially ownership-qualified</span> 802 if it is qualified with <tt>__autoreleasing</tt>, <tt>__strong</tt>, or 803 <tt>__weak</tt>.</p> 804 805 <div id="ownership.spelling"> 806 <h1>Spelling</h1> 807 808 <p>The names of the ownership qualifiers are reserved for the 809 implementation. A program may not assume that they are or are not 810 implemented with macros, or what those macros expand to.</p> 811 812 <p>An ownership qualifier may be written anywhere that any other type 813 qualifier may be written.</p> 814 815 <p>If an ownership qualifier appears in 816 the <i>declaration-specifiers</i>, the following rules apply:</p> 817 818 <ul> 819 <li>if the type specifier is a retainable object owner type, the 820 qualifier applies to that type;</li> 821 <li>if the outermost non-array part of the declarator is a pointer or 822 block pointer, the qualifier applies to that type;</li> 823 <li>otherwise the program is ill-formed.</li> 824 </ul> 825 826 <p>If an ownership qualifier appears on the declarator name, or on the 827 declared object, it is applied to outermost pointer or block-pointer 828 type.</p> 829 830 <p>If an ownership qualifier appears anywhere else in a declarator, it 831 applies to the type there.</p> 832 833 <div id="ownership.spelling.property"> 834 <h1>Property declarations</h1> 835 836 <p>A property of retainable object pointer type may have ownership. 837 If the property's type is ownership-qualified, then the property has 838 that ownership. If the property has one of the following modifiers, 839 then the property has the corresponding ownership. A property is 840 ill-formed if it has conflicting sources of ownership, or if it has 841 redundant ownership modifiers, or if it has <tt>__autoreleasing</tt> 842 ownership.</p> 843 844 <ul> 845 <li><tt>assign</tt> implies <tt>__unsafe_unretained</tt> ownership.</li> 846 <li><tt>copy</tt> implies <tt>__strong</tt> ownership, as well as the 847 usual behavior of copy semantics on the setter.</li> 848 <li><tt>retain</tt> implies <tt>__strong</tt> ownership.</li> 849 <li><tt>strong</tt> implies <tt>__strong</tt> ownership.</li> 850 <li><tt>unsafe_unretained</tt> implies <tt>__unsafe_unretained</tt> 851 ownership.</li> 852 <li><tt>weak</tt> implies <tt>__weak</tt> ownership.</li> 853 </ul> 854 855 <p>With the exception of <tt>weak</tt>, these modifiers are available 856 in non-ARC modes.</p> 857 858 <p>A property's specified ownership is preserved in its metadata, but 859 otherwise the meaning is purely conventional unless the property is 860 synthesized. If a property is synthesized, then the 861 <span class="term">associated instance variable</span> is the 862 instance variable which is named, possibly implicitly, by the 863 <tt>@synthesize</tt> declaration. If the associated instance variable 864 already exists, then its ownership qualification must equal the 865 ownership of the property; otherwise, the instance variable is created 866 with that ownership qualification.</p> 867 868 <p>A property of retainable object pointer type which is synthesized 869 without a source of ownership has the ownership of its associated 870 instance variable, if it already exists; otherwise, 871 <span class="revision"><span class="whenRevised">[beginning Apple 3.1, 872 LLVM 3.1]</span> its ownership is implicitly <tt>strong</tt></span>. 873 Prior to this revision, it was ill-formed to synthesize such a 874 property.</p> 875 876 <div class="rationale"><p>Rationale: using <tt>strong</tt> by default 877 is safe and consistent with the generic ARC rule about 878 <a href="#ownership.inference.variables">inferring ownership</a>. It 879 is, unfortunately, inconsistent with the non-ARC rule which states 880 that such properties are implicitly <tt>assign</tt>. However, that 881 rule is clearly untenable in ARC, since it leads to default-unsafe 882 code. The main merit to banning the properties is to avoid confusion 883 with non-ARC practice, which did not ultimately strike us as 884 sufficient to justify requiring extra syntax and (more importantly) 885 forcing novices to understand ownership rules just to declare a 886 property when the default is so reasonable. Changing the rule away 887 from non-ARC practice was acceptable because we had conservatively 888 banned the synthesis in order to give ourselves exactly this 889 leeway.</p></div> 890 891 <p>Applying <tt>__attribute__((NSObject))</tt> to a property not of 892 retainable object pointer type has the same behavior it does outside 893 of ARC: it requires the property type to be some sort of pointer and 894 permits the use of modifiers other than <tt>assign</tt>. These 895 modifiers only affect the synthesized getter and setter; direct 896 accesses to the ivar (even if synthesized) still have primitive 897 semantics, and the value in the ivar will not be automatically 898 released during deallocation.</p> 899 900 </div> <!-- ownership.spelling.property --> 901 902 </div> <!-- ownership.spelling --> 903 904 <div id="ownership.semantics"> 905 <h1>Semantics</h1> 906 907 <p>There are five <span class="term">managed operations</span> which 908 may be performed on an object of retainable object pointer type. Each 909 qualifier specifies different semantics for each of these operations. 910 It is still undefined behavior to access an object outside of its 911 lifetime.</p> 912 913 <p>A load or store with <q>primitive semantics</q> has the same 914 semantics as the respective operation would have on an <tt>void*</tt> 915 lvalue with the same alignment and non-ownership qualification.</p> 916 917 <p><span class="term">Reading</span> occurs when performing a 918 lvalue-to-rvalue conversion on an object lvalue.</p> 919 920 <ul> 921 <li>For <tt>__weak</tt> objects, the current pointee is retained and 922 then released at the end of the current full-expression. This must 923 execute atomically with respect to assignments and to the final 924 release of the pointee.</li> 925 <li>For all other objects, the lvalue is loaded with primitive 926 semantics.</li> 927 </ul> 928 929 <p><span class="term">Assignment</span> occurs when evaluating 930 an assignment operator. The semantics vary based on the qualification:</p> 931 <ul> 932 <li>For <tt>__strong</tt> objects, the new pointee is first retained; 933 second, the lvalue is loaded with primitive semantics; third, the new 934 pointee is stored into the lvalue with primitive semantics; and 935 finally, the old pointee is released. This is not performed 936 atomically; external synchronization must be used to make this safe in 937 the face of concurrent loads and stores.</li> 938 <li>For <tt>__weak</tt> objects, the lvalue is updated to point to the 939 new pointee, unless the new pointee is an object currently undergoing 940 deallocation, in which case the lvalue is updated to a null pointer. 941 This must execute atomically with respect to other assignments to the 942 object, to reads from the object, and to the final release of the new 943 pointee.</li> 944 <li>For <tt>__unsafe_unretained</tt> objects, the new pointee is 945 stored into the lvalue using primitive semantics.</li> 946 <li>For <tt>__autoreleasing</tt> objects, the new pointee is retained, 947 autoreleased, and stored into the lvalue using primitive semantics.</li> 948 </ul> 949 950 <p><span class="term">Initialization</span> occurs when an object's 951 lifetime begins, which depends on its storage duration. 952 Initialization proceeds in two stages:</p> 953 <ol> 954 <li>First, a null pointer is stored into the lvalue using primitive 955 semantics. This step is skipped if the object 956 is <tt>__unsafe_unretained</tt>.</li> 957 <li>Second, if the object has an initializer, that expression is 958 evaluated and then assigned into the object using the usual assignment 959 semantics.</li> 960 </ol> 961 962 <p><span class="term">Destruction</span> occurs when an object's 963 lifetime ends. In all cases it is semantically equivalent to 964 assigning a null pointer to the object, with the proviso that of 965 course the object cannot be legally read after the object's lifetime 966 ends.</p> 967 968 <p><span class="term">Moving</span> occurs in specific situations 969 where an lvalue is <q>moved from</q>, meaning that its current pointee 970 will be used but the object may be left in a different (but still 971 valid) state. This arises with <tt>__block</tt> variables and rvalue 972 references in C++. For <tt>__strong</tt> lvalues, moving is equivalent 973 to loading the lvalue with primitive semantics, writing a null pointer 974 to it with primitive semantics, and then releasing the result of the 975 load at the end of the current full-expression. For all other 976 lvalues, moving is equivalent to reading the object.</p> 977 978 </div> <!-- ownership.semantics --> 979 980 <div id="ownership.restrictions"> 981 <h1>Restrictions</h1> 982 983 <div id="ownership.restrictions.weak"> 984 <h1>Weak-unavailable types</h1> 985 986 <p>It is explicitly permitted for Objective-C classes to not 987 support <tt>__weak</tt> references. It is undefined behavior to 988 perform an operation with weak assignment semantics with a pointer to 989 an Objective-C object whose class does not support <tt>__weak</tt> 990 references.</p> 991 992 <div class="rationale"><p>Rationale: historically, it has been 993 possible for a class to provide its own reference-count implementation 994 by overriding <tt>retain</tt>, <tt>release</tt>, etc. However, weak 995 references to an object require coordination with its class's 996 reference-count implementation because, among other things, weak loads 997 and stores must be atomic with respect to the final release. 998 Therefore, existing custom reference-count implementations will 999 generally not support weak references without additional effort. This 1000 is unavoidable without breaking binary compatibility.</p></div> 1001 1002 <p>A class may indicate that it does not support weak references by 1003 providing the <tt>objc_arc_weak_unavailable</tt> attribute on the 1004 class's interface declaration. A retainable object pointer type 1005 is <span class="term">weak-unavailable</span> if is a pointer to an 1006 (optionally protocol-qualified) Objective-C class <tt>T</tt> 1007 where <tt>T</tt> or one of its superclasses has 1008 the <tt>objc_arc_weak_unavailable</tt> attribute. A program is 1009 ill-formed if it applies the <tt>__weak</tt> ownership qualifier to a 1010 weak-unavailable type or if the value operand of a weak assignment 1011 operation has a weak-unavailable type.</p> 1012 </div> <!-- ownership.restrictions.weak --> 1013 1014 <div id="ownership.restrictions.autoreleasing"> 1015 <h1>Storage duration of <tt>__autoreleasing</tt> objects</h1> 1016 1017 <p>A program is ill-formed if it declares an <tt>__autoreleasing</tt> 1018 object of non-automatic storage duration. A program is ill-formed 1019 if it captures an <tt>__autoreleasing</tt> object in a block or, 1020 unless by reference, in a C++11 lambda.</p> 1021 1022 <div class="rationale"><p>Rationale: autorelease pools are tied to the 1023 current thread and scope by their nature. While it is possible to 1024 have temporary objects whose instance variables are filled with 1025 autoreleased objects, there is no way that ARC can provide any sort of 1026 safety guarantee there.</p></div> 1027 1028 <p>It is undefined behavior if a non-null pointer is assigned to 1029 an <tt>__autoreleasing</tt> object while an autorelease pool is in 1030 scope and then that object is read after the autorelease pool's scope 1031 is left.</p> 1032 1033 </div> 1034 1035 <div id="ownership.restrictions.conversion.indirect"> 1036 <h1>Conversion of pointers to ownership-qualified types</h1> 1037 1038 <p>A program is ill-formed if an expression of type <tt>T*</tt> is 1039 converted, explicitly or implicitly, to the type <tt>U*</tt>, 1040 where <tt>T</tt> and <tt>U</tt> have different ownership 1041 qualification, unless:</p> 1042 <ul> 1043 <li><tt>T</tt> is qualified with <tt>__strong</tt>, 1044 <tt>__autoreleasing</tt>, or <tt>__unsafe_unretained</tt>, and 1045 <tt>U</tt> is qualified with both <tt>const</tt> and 1046 <tt>__unsafe_unretained</tt>; or</li> 1047 <li>either <tt>T</tt> or <tt>U</tt> is <tt>cv void</tt>, where 1048 <tt>cv</tt> is an optional sequence of non-ownership qualifiers; or</li> 1049 <li>the conversion is requested with a <tt>reinterpret_cast</tt> in 1050 Objective-C++; or</li> 1051 <li>the conversion is a 1052 well-formed <a href="#ownership.restrictions.pass_by_writeback">pass-by-writeback</a>.</li> 1053 </ul> 1054 1055 <p>The analogous rule applies to <tt>T&amp;</tt> and <tt>U&amp;</tt> in 1056 Objective-C++.</p> 1057 1058 <div class="rationale"><p>Rationale: these rules provide a reasonable 1059 level of type-safety for indirect pointers, as long as the underlying 1060 memory is not deallocated. The conversion to <tt>const 1061 __unsafe_unretained</tt> is permitted because the semantics of reads 1062 are equivalent across all these ownership semantics, and that's a very 1063 useful and common pattern. The interconversion with <tt>void*</tt> is 1064 useful for allocating memory or otherwise escaping the type system, 1065 but use it carefully. <tt>reinterpret_cast</tt> is considered to be 1066 an obvious enough sign of taking responsibility for any 1067 problems.</p></div> 1068 1069 <p>It is undefined behavior to access an ownership-qualified object 1070 through an lvalue of a differently-qualified type, except that any 1071 non-<tt>__weak</tt> object may be read through 1072 an <tt>__unsafe_unretained</tt> lvalue.</p> 1073 1074 <p>It is undefined behavior if a managed operation is performed on 1075 a <tt>__strong</tt> or <tt>__weak</tt> object without a guarantee that 1076 it contains a primitive zero bit-pattern, or if the storage for such 1077 an object is freed or reused without the object being first assigned a 1078 null pointer.</p> 1079 1080 <div class="rationale"><p>Rationale: ARC cannot differentiate between 1081 an assignment operator which is intended to <q>initialize</q> dynamic 1082 memory and one which is intended to potentially replace a value. 1083 Therefore the object's pointer must be valid before letting ARC at it. 1084 Similarly, C and Objective-C do not provide any language hooks for 1085 destroying objects held in dynamic memory, so it is the programmer's 1086 responsibility to avoid leaks (<tt>__strong</tt> objects) and 1087 consistency errors (<tt>__weak</tt> objects).</p> 1088 1089 <p>These requirements are followed automatically in Objective-C++ when 1090 creating objects of retainable object owner type with <tt>new</tt> 1091 or <tt>new[]</tt> and destroying them with <tt>delete</tt>, 1092 <tt>delete[]</tt>, or a pseudo-destructor expression. Note that 1093 arrays of nontrivially-ownership-qualified type are not ABI compatible 1094 with non-ARC code because the element type is non-POD: such arrays 1095 that are <tt>new[]</tt>'d in ARC translation units cannot 1096 be <tt>delete[]</tt>'d in non-ARC translation units and 1097 vice-versa.</p></div> 1098 1099 </div> 1100 1101 <div id="ownership.restrictions.pass_by_writeback"> 1102 <h1>Passing to an out parameter by writeback</h1> 1103 1104 <p>If the argument passed to a parameter of type 1105 <tt>T __autoreleasing *</tt> has type <tt>U oq *</tt>, 1106 where <tt>oq</tt> is an ownership qualifier, then the argument is a 1107 candidate for <span class="term">pass-by-writeback</span> if:</p> 1108 1109 <ul> 1110 <li><tt>oq</tt> is <tt>__strong</tt> or <tt>__weak</tt>, and</li> 1111 <li>it would be legal to initialize a <tt>T __strong *</tt> with 1112 a <tt>U __strong *</tt>.</li> 1113 </ul> 1114 1115 <p>For purposes of overload resolution, an implicit conversion 1116 sequence requiring a pass-by-writeback is always worse than an 1117 implicit conversion sequence not requiring a pass-by-writeback.</p> 1118 1119 <p>The pass-by-writeback is ill-formed if the argument expression does 1120 not have a legal form:</p> 1121 1122 <ul> 1123 <li><tt>&amp;var</tt>, where <tt>var</tt> is a scalar variable of 1124 automatic storage duration with retainable object pointer type</li> 1125 <li>a conditional expression where the second and third operands are 1126 both legal forms</li> 1127 <li>a cast whose operand is a legal form</li> 1128 <li>a null pointer constant</li> 1129 </ul> 1130 1131 <div class="rationale"><p>Rationale: the restriction in the form of 1132 the argument serves two purposes. First, it makes it impossible to 1133 pass the address of an array to the argument, which serves to protect 1134 against an otherwise serious risk of mis-inferring an <q>array</q> 1135 argument as an out-parameter. Second, it makes it much less likely 1136 that the user will see confusing aliasing problems due to the 1137 implementation, below, where their store to the writeback temporary is 1138 not immediately seen in the original argument variable.</p></div> 1139 1140 <p>A pass-by-writeback is evaluated as follows:</p> 1141 <ol> 1142 <li>The argument is evaluated to yield a pointer <tt>p</tt> of 1143 type <tt>U oq *</tt>.</li> 1144 <li>If <tt>p</tt> is a null pointer, then a null pointer is passed as 1145 the argument, and no further work is required for the pass-by-writeback.</li> 1146 <li>Otherwise, a temporary of type <tt>T __autoreleasing</tt> is 1147 created and initialized to a null pointer.</li> 1148 <li>If the parameter is not an Objective-C method parameter marked 1149 <tt>out</tt>, then <tt>*p</tt> is read, and the result is written 1150 into the temporary with primitive semantics.</li> 1151 <li>The address of the temporary is passed as the argument to the 1152 actual call.</li> 1153 <li>After the call completes, the temporary is loaded with primitive 1154 semantics, and that value is assigned into <tt>*p</tt>.</li> 1155 </ol> 1156 1157 <div class="rationale"><p>Rationale: this is all admittedly 1158 convoluted. In an ideal world, we would see that a local variable is 1159 being passed to an out-parameter and retroactively modify its type to 1160 be <tt>__autoreleasing</tt> rather than <tt>__strong</tt>. This would 1161 be remarkably difficult and not always well-founded under the C type 1162 system. However, it was judged unacceptably invasive to require 1163 programmers to write <tt>__autoreleasing</tt> on all the variables 1164 they intend to use for out-parameters. This was the least bad 1165 solution.</p></div> 1166 1167 </div> 1168 1169 <div id="ownership.restrictions.records"> 1170 <h1>Ownership-qualified fields of structs and unions</h1> 1171 1172 <p>A program is ill-formed if it declares a member of a C struct or 1173 union to have a nontrivially ownership-qualified type.</p> 1174 1175 <div class="rationale"><p>Rationale: the resulting type would be 1176 non-POD in the C++ sense, but C does not give us very good language 1177 tools for managing the lifetime of aggregates, so it is more 1178 convenient to simply forbid them. It is still possible to manage this 1179 with a <tt>void*</tt> or an <tt>__unsafe_unretained</tt> 1180 object.</p></div> 1181 1182 <p>This restriction does not apply in Objective-C++. However, 1183 nontrivally ownership-qualified types are considered non-POD: in C++11 1184 terms, they are not trivially default constructible, copy 1185 constructible, move constructible, copy assignable, move assignable, 1186 or destructible. It is a violation of C++'s One Definition Rule to use 1187 a class outside of ARC that, under ARC, would have a nontrivially 1188 ownership-qualified member.</p> 1189 1190 <div class="rationale"><p>Rationale: unlike in C, we can express all 1191 the necessary ARC semantics for ownership-qualified subobjects as 1192 suboperations of the (default) special member functions for the class. 1193 These functions then become non-trivial. This has the non-obvious 1194 result that the class will have a non-trivial copy constructor and 1195 non-trivial destructor; if this would not normally be true outside of 1196 ARC, objects of the type will be passed and returned in an 1197 ABI-incompatible manner.</p></div> 1198 1199 </div> 1200 1201 </div> 1202 1203 <div id="ownership.inference"> 1204 <h1>Ownership inference</h1> 1205 1206 <div id="ownership.inference.variables"> 1207 <h1>Objects</h1> 1208 1209 <p>If an object is declared with retainable object owner type, but 1210 without an explicit ownership qualifier, its type is implicitly 1211 adjusted to have <tt>__strong</tt> qualification.</p> 1212 1213 <p>As a special case, if the object's base type is <tt>Class</tt> 1214 (possibly protocol-qualified), the type is adjusted to 1215 have <tt>__unsafe_unretained</tt> qualification instead.</p> 1216 1217 </div> 1218 1219 <div id="ownership.inference.indirect_parameters"> 1220 <h1>Indirect parameters</h1> 1221 1222 <p>If a function or method parameter has type <tt>T*</tt>, where 1223 <tt>T</tt> is an ownership-unqualified retainable object pointer type, 1224 then:</p> 1225 1226 <ul> 1227 <li>if <tt>T</tt> is <tt>const</tt>-qualified or <tt>Class</tt>, then 1228 it is implicitly qualified with <tt>__unsafe_unretained</tt>;</li> 1229 <li>otherwise, it is implicitly qualified 1230 with <tt>__autoreleasing</tt>.</li> 1231 </ul> 1232 1233 <div class="rationale"><p>Rationale: <tt>__autoreleasing</tt> exists 1234 mostly for this case, the Cocoa convention for out-parameters. Since 1235 a pointer to <tt>const</tt> is obviously not an out-parameter, we 1236 instead use a type more useful for passing arrays. If the user 1237 instead intends to pass in a <em>mutable</em> array, inferring 1238 <tt>__autoreleasing</tt> is the wrong thing to do; this directs some 1239 of the caution in the following rules about writeback.</p></div> 1240 1241 <p>Such a type written anywhere else would be ill-formed by the 1242 general rule requiring ownership qualifiers.</p> 1243 1244 <p>This rule does not apply in Objective-C++ if a parameter's type is 1245 dependent in a template pattern and is only <em>instantiated</em> to 1246 a type which would be a pointer to an unqualified retainable object 1247 pointer type. Such code is still ill-formed.</p> 1248 1249 <div class="rationale"><p>Rationale: the convention is very unlikely 1250 to be intentional in template code.</p></div> 1251 1252 </div> <!-- ownership.inference.indirect_parameters --> 1253 1254 <div id="ownership.inference.template_arguments"> 1255 <h1>Template arguments</h1> 1256 1257 <p>If a template argument for a template type parameter is an 1258 retainable object owner type that does not have an explicit ownership 1259 qualifier, it is adjusted to have <tt>__strong</tt> 1260 qualification. This adjustment occurs regardless of whether the 1261 template argument was deduced or explicitly specified. </p> 1262 1263 <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> 1264 1265 </div> <!-- ownership.inference.template_arguments --> 1266 </div> <!-- ownership.inference --> 1267 </div> <!-- ownership --> 1268 1269 1270 <div id="family"> 1271 <h1>Method families</h1> 1272 1273 <p>An Objective-C method may fall into a <span class="term">method 1274 family</span>, which is a conventional set of behaviors ascribed to it 1275 by the Cocoa conventions.</p> 1276 1277 <p>A method is in a certain method family if:</p> 1278 <ul> 1279 <li>it has a <tt>objc_method_family</tt> attribute placing it in that 1280 family; or if not that,</li> 1281 <li>it does not have an <tt>objc_method_family</tt> attribute placing 1282 it in a different or no family, and</li> 1283 <li>its selector falls into the corresponding selector family, and</li> 1284 <li>its signature obeys the added restrictions of the method family.</li> 1285 </ul> 1286 1287 <p>A selector is in a certain selector family if, ignoring any leading 1288 underscores, the first component of the selector either consists 1289 entirely of the name of the method family or it begins with that name 1290 followed by a character other than a lowercase letter. For 1291 example, <tt>_perform:with:</tt> and <tt>performWith:</tt> would fall 1292 into the <tt>perform</tt> family (if we recognized one), 1293 but <tt>performing:with</tt> would not.</p> 1294 1295 <p>The families and their added restrictions are:</p> 1296 1297 <ul> 1298 <li><tt>alloc</tt> methods must return a retainable object pointer type.</li> 1299 <li><tt>copy</tt> methods must return a retainable object pointer type.</li> 1300 <li><tt>mutableCopy</tt> methods must return a retainable object pointer type.</li> 1301 <li><tt>new</tt> methods must return a retainable object pointer type.</li> 1302 <li><tt>init</tt> methods must be instance methods and must return an 1303 Objective-C pointer type. Additionally, a program is ill-formed if it 1304 declares or contains a call to an <tt>init</tt> method whose return 1305 type is neither <tt>id</tt> nor a pointer to a super-class or 1306 sub-class of the declaring class (if the method was declared on 1307 a class) or the static receiver type of the call (if it was declared 1308 on a protocol). 1309 1310 <div class="rationale"><p>Rationale: there are a fair number of existing 1311 methods with <tt>init</tt>-like selectors which nonetheless don't 1312 follow the <tt>init</tt> conventions. Typically these are either 1313 accidental naming collisions or helper methods called during 1314 initialization. Because of the peculiar retain/release behavior 1315 of <tt>init</tt> methods, it's very important not to treat these 1316 methods as <tt>init</tt> methods if they aren't meant to be. It was 1317 felt that implicitly defining these methods out of the family based on 1318 the exact relationship between the return type and the declaring class 1319 would be much too subtle and fragile. Therefore we identify a small 1320 number of legitimate-seeming return types and call everything else an 1321 error. This serves the secondary purpose of encouraging programmers 1322 not to accidentally give methods names in the <tt>init</tt> family.</p> 1323 1324 <p>Note that a method with an <tt>init</tt>-family selector which 1325 returns a non-Objective-C type (e.g. <tt>void</tt>) is perfectly 1326 well-formed; it simply isn't in the <tt>init</tt> family.</p></div> 1327 </li> 1328 </ul> 1329 1330 <p>A program is ill-formed if a method's declarations, 1331 implementations, and overrides do not all have the same method 1332 family.</p> 1333 1334 <div id="family.attribute"> 1335 <h1>Explicit method family control</h1> 1336 1337 <p>A method may be annotated with the <tt>objc_method_family</tt> 1338 attribute to precisely control which method family it belongs to. If 1339 a method in an <tt>@implementation</tt> does not have this attribute, 1340 but there is a method declared in the corresponding <tt>@interface</tt> 1341 that does, then the attribute is copied to the declaration in the 1342 <tt>@implementation</tt>. The attribute is available outside of ARC, 1343 and may be tested for with the preprocessor query 1344 <tt>__has_attribute(objc_method_family)</tt>.</p> 1345 1346 <p>The attribute is spelled 1347 <tt>__attribute__((objc_method_family(<i>family</i>)))</tt>. 1348 If <i>family</i> is <tt>none</tt>, the method has no family, even if 1349 it would otherwise be considered to have one based on its selector and 1350 type. Otherwise, <i>family</i> must be one 1351 of <tt>alloc</tt>, <tt>copy</tt>, <tt>init</tt>, 1352 <tt>mutableCopy</tt>, or <tt>new</tt>, in which case the method is 1353 considered to belong to the corresponding family regardless of its 1354 selector. It is an error if a method that is explicitly added to a 1355 family in this way does not meet the requirements of the family other 1356 than the selector naming convention.</p> 1357 1358 <div class="rationale"><p>Rationale: the rules codified in this document 1359 describe the standard conventions of Objective-C. However, as these 1360 conventions have not heretofore been enforced by an unforgiving 1361 mechanical system, they are only imperfectly kept, especially as they 1362 haven't always even been precisely defined. While it is possible to 1363 define low-level ownership semantics with attributes like 1364 <tt>ns_returns_retained</tt>, this attribute allows the user to 1365 communicate semantic intent, which is of use both to ARC (which, e.g., 1366 treats calls to <tt>init</tt> specially) and the static analyzer.</p></div> 1367 </div> 1368 1369 <div id="family.semantics"> 1370 <h1>Semantics of method families</h1> 1371 1372 <p>A method's membership in a method family may imply non-standard 1373 semantics for its parameters and return type.</p> 1374 1375 <p>Methods in the <tt>alloc</tt>, <tt>copy</tt>, <tt>mutableCopy</tt>, 1376 and <tt>new</tt> families &mdash; that is, methods in all the 1377 currently-defined families except <tt>init</tt> &mdash; implicitly 1378 <a href="#objects.operands.retained_returns">return a retained 1379 object</a> as if they were annotated with 1380 the <tt>ns_returns_retained</tt> attribute. This can be overridden by 1381 annotating the method with either of 1382 the <tt>ns_returns_autoreleased</tt> or 1383 <tt>ns_returns_not_retained</tt> attributes.</p> 1384 1385 <p>Properties also follow same naming rules as methods. This means that 1386 those in the <tt>alloc</tt>, <tt>copy</tt>, <tt>mutableCopy</tt>, 1387 and <tt>new</tt> families provide access to 1388 <a href="#objects.operands.retained_returns">retained objects</a>. 1389 This can be overridden by annotating the property with 1390 <tt>ns_returns_not_retained</tt> attribute.</p> 1391 1392 <div id="family.semantics.init"> 1393 <h1>Semantics of <tt>init</tt></h1> 1394 <p>Methods in the <tt>init</tt> family implicitly 1395 <a href="#objects.operands.consumed">consume</a> their <tt>self</tt> 1396 parameter and <a href="#objects.operands.retained_returns">return a 1397 retained object</a>. Neither of these properties can be altered 1398 through attributes.</p> 1399 1400 <p>A call to an <tt>init</tt> method with a receiver that is either 1401 <tt>self</tt> (possibly parenthesized or casted) or <tt>super</tt> is 1402 called a <span class="term">delegate init call</span>. It is an error 1403 for a delegate init call to be made except from an <tt>init</tt> 1404 method, and excluding blocks within such methods.</p> 1405 1406 <p>As an exception to the <a href="misc.self">usual rule</a>, the 1407 variable <tt>self</tt> is mutable in an <tt>init</tt> method and has 1408 the usual semantics for a <tt>__strong</tt> variable. However, it is 1409 undefined behavior and the program is ill-formed, no diagnostic 1410 required, if an <tt>init</tt> method attempts to use the previous 1411 value of <tt>self</tt> after the completion of a delegate init call. 1412 It is conventional, but not required, for an <tt>init</tt> method to 1413 return <tt>self</tt>.</p> 1414 1415 <p>It is undefined behavior for a program to cause two or more calls 1416 to <tt>init</tt> methods on the same object, except that 1417 each <tt>init</tt> method invocation may perform at most one delegate 1418 init call.</p> 1419 1420 </div> <!-- family.semantics.init --> 1421 1422 <div id="family.semantics.result_type"> 1423 <h1>Related result types</h1> 1424 1425 <p>Certain methods are candidates to have <span class="term">related 1426 result types</span>:</p> 1427 <ul> 1428 <li>class methods in the <tt>alloc</tt> and <tt>new</tt> method families</li> 1429 <li>instance methods in the <tt>init</tt> family</li> 1430 <li>the instance method <tt>self</tt></li> 1431 <li>outside of ARC, the instance methods <tt>retain</tt> and <tt>autorelease</tt></li> 1432 </ul> 1433 1434 <p>If the formal result type of such a method is <tt>id</tt> or 1435 protocol-qualified <tt>id</tt>, or a type equal to the declaring class 1436 or a superclass, then it is said to have a related result type. In 1437 this case, when invoked in an explicit message send, it is assumed to 1438 return a type related to the type of the receiver:</p> 1439 1440 <ul> 1441 <li>if it is a class method, and the receiver is a class 1442 name <tt>T</tt>, the message send expression has type <tt>T*</tt>; 1443 otherwise</li> 1444 <li>if it is an instance method, and the receiver has type <tt>T</tt>, 1445 the message send expression has type <tt>T</tt>; otherwise</li> 1446 <li>the message send expression has the normal result type of the 1447 method.</li> 1448 </ul> 1449 1450 <p>This is a new rule of the Objective-C language and applies outside 1451 of ARC.</p> 1452 1453 <div class="rationale"><p>Rationale: ARC's automatic code emission is 1454 more prone than most code to signature errors, i.e. errors where a 1455 call was emitted against one method signature, but the implementing 1456 method has an incompatible signature. Having more precise type 1457 information helps drastically lower this risk, as well as catching 1458 a number of latent bugs.</p></div> 1459 1460 </div> <!-- family.semantics.result_type --> 1461 </div> <!-- family.semantics --> 1462 </div> <!-- family --> 1463 1464 <div id="optimization"> 1465 <h1>Optimization</h1> 1466 1467 <p>ARC applies aggressive rules for the optimization of local 1468 behavior. These rules are based around a core assumption of 1469 <span class="term">local balancing</span>: that other code will 1470 perform retains and releases as necessary (and only as necessary) for 1471 its own safety, and so the optimizer does not need to consider global 1472 properties of the retain and release sequence. For example, if a 1473 retain and release immediately bracket a call, the optimizer can 1474 delete the retain and release on the assumption that the called 1475 function will not do a constant number of unmotivated releases 1476 followed by a constant number of <q>balancing</q> retains, such that 1477 the local retain/release pair is the only thing preventing the called 1478 function from ending up with a dangling reference.</p> 1479 1480 <p>The optimizer assumes that when a new value enters local control, 1481 e.g. from a load of a non-local object or as the result of a function 1482 call, it is instaneously valid. Subsequently, a retain and release of 1483 a value are necessary on a computation path only if there is a use of 1484 that value before the release and after any operation which might 1485 cause a release of the value (including indirectly or non-locally), 1486 and only if the value is not demonstrably already retained.</p> 1487 1488 <p>The complete optimization rules are quite complicated, but it would 1489 still be useful to document them here.</p> 1490 1491 <div id="optimization.precise"> 1492 <h1>Precise lifetime semantics</h1> 1493 1494 <p>In general, ARC maintains an invariant that a retainable object 1495 pointer held in a <tt>__strong</tt> object will be retained for the 1496 full formal lifetime of the object. Objects subject to this invariant 1497 have <span class="term">precise lifetime semantics</span>.</p> 1498 1499 <p>By default, local variables of automatic storage duration do not 1500 have precise lifetime semantics. Such objects are simply strong 1501 references which hold values of retainable object pointer type, and 1502 these values are still fully subject to the optimizations on values 1503 under local control.</p> 1504 1505 <div class="rationale"><p>Rationale: applying these precise-lifetime 1506 semantics strictly would be prohibitive. Many useful optimizations 1507 that might theoretically decrease the lifetime of an object would be 1508 rendered impossible. Essentially, it promises too much.</p></div> 1509 1510 <p>A local variable of retainable object owner type and automatic 1511 storage duration may be annotated with the <tt>objc_precise_lifetime</tt> 1512 attribute to indicate that it should be considered to be an object 1513 with precise lifetime semantics.</p> 1514 1515 <div class="rationale"><p>Rationale: nonetheless, it is sometimes 1516 useful to be able to force an object to be released at a precise time, 1517 even if that object does not appear to be used. This is likely to be 1518 uncommon enough that the syntactic weight of explicitly requesting 1519 these semantics will not be burdensome, and may even make the code 1520 clearer.</p></div> 1521 1522 </div> <!-- optimization.precise --> 1523 1524 </div> <!-- optimization --> 1525 1526 <div id="misc"> 1527 <h1>Miscellaneous</h1> 1528 1529 <div id="misc.special_methods"> 1530 <h1>Special methods</h1> 1531 1532 <div id="misc.special_methods.retain"> 1533 <h1>Memory management methods</h1> 1534 1535 <p>A program is ill-formed if it contains a method definition, message 1536 send, or <tt>@selector</tt> expression for any of the following 1537 selectors:</p> 1538 <ul> 1539 <li><tt>autorelease</tt></li> 1540 <li><tt>release</tt></li> 1541 <li><tt>retain</tt></li> 1542 <li><tt>retainCount</tt></li> 1543 </ul> 1544 1545 <div class="rationale"><p>Rationale: <tt>retainCount</tt> is banned 1546 because ARC robs it of consistent semantics. The others were banned 1547 after weighing three options for how to deal with message sends:</p> 1548 1549 <p><b>Honoring</b> them would work out very poorly if a programmer 1550 naively or accidentally tried to incorporate code written for manual 1551 retain/release code into an ARC program. At best, such code would do 1552 twice as much work as necessary; quite frequently, however, ARC and 1553 the explicit code would both try to balance the same retain, leading 1554 to crashes. The cost is losing the ability to perform <q>unrooted</q> 1555 retains, i.e. retains not logically corresponding to a strong 1556 reference in the object graph.</p> 1557 1558 <p><b>Ignoring</b> them would badly violate user expectations about their 1559 code. While it <em>would</em> make it easier to develop code simultaneously 1560 for ARC and non-ARC, there is very little reason to do so except for 1561 certain library developers. ARC and non-ARC translation units share 1562 an execution model and can seamlessly interoperate. Within a 1563 translation unit, a developer who faithfully maintains their code in 1564 non-ARC mode is suffering all the restrictions of ARC for zero 1565 benefit, while a developer who isn't testing the non-ARC mode is 1566 likely to be unpleasantly surprised if they try to go back to it.</p> 1567 1568 <p><b>Banning</b> them has the disadvantage of making it very awkward 1569 to migrate existing code to ARC. The best answer to that, given a 1570 number of other changes and restrictions in ARC, is to provide a 1571 specialized tool to assist users in that migration.</p> 1572 1573 <p>Implementing these methods was banned because they are too integral 1574 to the semantics of ARC; many tricks which worked tolerably under 1575 manual reference counting will misbehave if ARC performs an ephemeral 1576 extra retain or two. If absolutely required, it is still possible to 1577 implement them in non-ARC code, for example in a category; the 1578 implementations must obey the <a href="#objects.retains">semantics</a> 1579 laid out elsewhere in this document.</p> 1580 1581 </div> 1582 </div> <!-- misc.special_methods.retain --> 1583 1584 <div id="misc.special_methods.dealloc"> 1585 <h1><tt>dealloc</tt></h1> 1586 1587 <p>A program is ill-formed if it contains a message send 1588 or <tt>@selector</tt> expression for the selector <tt>dealloc</tt>.</p> 1589 1590 <div class="rationale"><p>Rationale: there are no legitimate reasons 1591 to call <tt>dealloc</tt> directly.</p></div> 1592 1593 <p>A class may provide a method definition for an instance method 1594 named <tt>dealloc</tt>. This method will be called after the final 1595 <tt>release</tt> of the object but before it is deallocated or any of 1596 its instance variables are destroyed. The superclass's implementation 1597 of <tt>dealloc</tt> will be called automatically when the method 1598 returns.</p> 1599 1600 <div class="rationale"><p>Rationale: even though ARC destroys instance 1601 variables automatically, there are still legitimate reasons to write 1602 a <tt>dealloc</tt> method, such as freeing non-retainable resources. 1603 Failing to call <tt>[super&nbsp;dealloc]</tt> in such a method is nearly 1604 always a bug. Sometimes, the object is simply trying to prevent 1605 itself from being destroyed, but <tt>dealloc</tt> is really far too 1606 late for the object to be raising such objections. Somewhat more 1607 legitimately, an object may have been pool-allocated and should not be 1608 deallocated with <tt>free</tt>; for now, this can only be supported 1609 with a <tt>dealloc</tt> implementation outside of ARC. Such an 1610 implementation must be very careful to do all the other work 1611 that <tt>NSObject</tt>'s <tt>dealloc</tt> would, which is outside the 1612 scope of this document to describe.</p></div> 1613 1614 <p>The instance variables for an ARC-compiled class will be destroyed 1615 at some point after control enters the <tt>dealloc</tt> method for the 1616 root class of the class. The ordering of the destruction of instance 1617 variables is unspecified, both within a single class and between 1618 subclasses and superclasses.</p> 1619 1620 <div class="rationale"><p>Rationale: the traditional, non-ARC pattern 1621 for destroying instance variables is to destroy them immediately 1622 before calling <tt>[super&nbsp;dealloc]</tt>. Unfortunately, message 1623 sends from the superclass are quite capable of reaching methods in the 1624 subclass, and those methods may well read or write to those instance 1625 variables. Making such message sends from dealloc is generally 1626 discouraged, since the subclass may well rely on other invariants that 1627 were broken during <tt>dealloc</tt>, but it's not so inescapably 1628 dangerous that we felt comfortable calling it undefined behavior. 1629 Therefore we chose to delay destroying the instance variables to a 1630 point at which message sends are clearly disallowed: the point at 1631 which the root class's deallocation routines take over.</p> 1632 1633 <p>In most code, the difference is not observable. It can, however, 1634 be observed if an instance variable holds a strong reference to an 1635 object whose deallocation will trigger a side-effect which must be 1636 carefully ordered with respect to the destruction of the super class. 1637 Such code violates the design principle that semantically important 1638 behavior should be explicit. A simple fix is to clear the instance 1639 variable manually during <tt>dealloc</tt>; a more holistic solution is 1640 to move semantically important side-effects out of 1641 <tt>dealloc</tt> and into a separate teardown phase which can rely on 1642 working with well-formed objects.</p></div> 1643 1644 </div> 1645 1646 </div> <!-- misc.special_methods --> 1647 1648 <div id="autoreleasepool"> 1649 <h1><tt>@autoreleasepool</tt></h1> 1650 1651 <p>To simplify the use of autorelease pools, and to bring them under 1652 the control of the compiler, a new kind of statement is available in 1653 Objective-C. It is written <tt>@autoreleasepool</tt> followed by 1654 a <i>compound-statement</i>, i.e. by a new scope delimited by curly 1655 braces. Upon entry to this block, the current state of the 1656 autorelease pool is captured. When the block is exited normally, 1657 whether by fallthrough or directed control flow (such 1658 as <tt>return</tt> or <tt>break</tt>), the autorelease pool is 1659 restored to the saved state, releasing all the objects in it. When 1660 the block is exited with an exception, the pool is not drained.</p> 1661 1662 <p><tt>@autoreleasepool</tt> may be used in non-ARC translation units, 1663 with equivalent semantics.</p> 1664 1665 <p>A program is ill-formed if it refers to the 1666 <tt>NSAutoreleasePool</tt> class.</p> 1667 1668 <div class="rationale"><p>Rationale: autorelease pools are clearly 1669 important for the compiler to reason about, but it is far too much to 1670 expect the compiler to accurately reason about control dependencies 1671 between two calls. It is also very easy to accidentally forget to 1672 drain an autorelease pool when using the manual API, and this can 1673 significantly inflate the process's high-water-mark. The introduction 1674 of a new scope is unfortunate but basically required for sane 1675 interaction with the rest of the language. Not draining the pool 1676 during an unwind is apparently required by the Objective-C exceptions 1677 implementation.</p></div> 1678 1679 </div> <!-- autoreleasepool --> 1680 1681 <div id="misc.self"> 1682 <h1><tt>self</tt></h1> 1683 1684 <p>The <tt>self</tt> parameter variable of an Objective-C method is 1685 never actually retained by the implementation. It is undefined 1686 behavior, or at least dangerous, to cause an object to be deallocated 1687 during a message send to that object.</p> 1688 1689 <p>To make this safe, for Objective-C instance methods <tt>self</tt> is 1690 implicitly <tt>const</tt> unless the method is in the <a 1691 href="#family.semantics.init"><tt>init</tt> family</a>. Further, <tt>self</tt> 1692 is <b>always</b> implicitly <tt>const</tt> within a class method.</p> 1693 1694 <div class="rationale"><p>Rationale: the cost of 1695 retaining <tt>self</tt> in all methods was found to be prohibitive, as 1696 it tends to be live across calls, preventing the optimizer from 1697 proving that the retain and release are unnecessary &mdash; for good 1698 reason, as it's quite possible in theory to cause an object to be 1699 deallocated during its execution without this retain and release. 1700 Since it's extremely uncommon to actually do so, even unintentionally, 1701 and since there's no natural way for the programmer to remove this 1702 retain/release pair otherwise (as there is for other parameters by, 1703 say, making the variable <tt>__unsafe_unretained</tt>), we chose to 1704 make this optimizing assumption and shift some amount of risk to the 1705 user.</p></div> 1706 1707 </div> <!-- misc.self --> 1708 1709 <div id="misc.enumeration"> 1710 <h1>Fast enumeration iteration variables</h1> 1711 1712 <p>If a variable is declared in the condition of an Objective-C fast 1713 enumeration loop, and the variable has no explicit ownership 1714 qualifier, then it is qualified with <tt>const __strong</tt> and 1715 objects encountered during the enumeration are not actually 1716 retained.</p> 1717 1718 <div class="rationale"><p>Rationale: this is an optimization made 1719 possible because fast enumeration loops promise to keep the objects 1720 retained during enumeration, and the collection itself cannot be 1721 synchronously modified. It can be overridden by explicitly qualifying 1722 the variable with <tt>__strong</tt>, which will make the variable 1723 mutable again and cause the loop to retain the objects it 1724 encounters.</p></div> 1725 1726 </div> <!-- misc.enumeration --> 1727 1728 <div id="misc.blocks"> 1729 <h1>Blocks</h1> 1730 1731 <p>The implicit <tt>const</tt> capture variables created when 1732 evaluating a block literal expression have the same ownership 1733 semantics as the local variables they capture. The capture is 1734 performed by reading from the captured variable and initializing the 1735 capture variable with that value; the capture variable is destroyed 1736 when the block literal is, i.e. at the end of the enclosing scope.</p> 1737 1738 <p>The <a href="#ownership.inference">inference</a> rules apply 1739 equally to <tt>__block</tt> variables, which is a shift in semantics 1740 from non-ARC, where <tt>__block</tt> variables did not implicitly 1741 retain during capture.</p> 1742 1743 <p><tt>__block</tt> variables of retainable object owner type are 1744 moved off the stack by initializing the heap copy with the result of 1745 moving from the stack copy.</p> 1746 1747 <p>With the exception of retains done as part of initializing 1748 a <tt>__strong</tt> parameter variable or reading a <tt>__weak</tt> 1749 variable, whenever these semantics call for retaining a value of 1750 block-pointer type, it has the effect of a <tt>Block_copy</tt>. The 1751 optimizer may remove such copies when it sees that the result is 1752 used only as an argument to a call.</p> 1753 1754 </div> <!-- misc.blocks --> 1755 1756 <div id="misc.exceptions"> 1757 <h1>Exceptions</h1> 1758 1759 <p>By default in Objective C, ARC is not exception-safe for normal 1760 releases:</p> 1761 <ul> 1762 <li>It does not end the lifetime of <tt>__strong</tt> variables when 1763 their scopes are abnormally terminated by an exception.</li> 1764 <li>It does not perform releases which would occur at the end of 1765 a full-expression if that full-expression throws an exception.</li> 1766 </ul> 1767 1768 <p>A program may be compiled with the option 1769 <tt>-fobjc-arc-exceptions</tt> in order to enable these, or with the 1770 option <tt>-fno-objc-arc-exceptions</tt> to explicitly disable them, 1771 with the last such argument <q>winning</q>.</p> 1772 1773 <div class="rationale"><p>Rationale: the standard Cocoa convention is 1774 that exceptions signal programmer error and are not intended to be 1775 recovered from. Making code exceptions-safe by default would impose 1776 severe runtime and code size penalties on code that typically does not 1777 actually care about exceptions safety. Therefore, ARC-generated code 1778 leaks by default on exceptions, which is just fine if the process is 1779 going to be immediately terminated anyway. Programs which do care 1780 about recovering from exceptions should enable the option.</p></div> 1781 1782 <p>In Objective-C++, <tt>-fobjc-arc-exceptions</tt> is enabled by 1783 default.</p> 1784 1785 <div class="rationale"><p>Rationale: C++ already introduces pervasive 1786 exceptions-cleanup code of the sort that ARC introduces. C++ 1787 programmers who have not already disabled exceptions are much more 1788 likely to actual require exception-safety.</p></div> 1789 1790 <p>ARC does end the lifetimes of <tt>__weak</tt> objects when an 1791 exception terminates their scope unless exceptions are disabled in the 1792 compiler.</p> 1793 1794 <div class="rationale"><p>Rationale: the consequence of a 1795 local <tt>__weak</tt> object not being destroyed is very likely to be 1796 corruption of the Objective-C runtime, so we want to be safer here. 1797 Of course, potentially massive leaks are about as likely to take down 1798 the process as this corruption is if the program does try to recover 1799 from exceptions.</p></div> 1800 1801 </div> <!-- misc.exceptions --> 1802 1803 <div id="misc.interior"> 1804 <h1>Interior pointers</h1> 1805 1806 <p>An Objective-C method returning a non-retainable pointer may be 1807 annotated with the <tt>objc_returns_inner_pointer</tt> attribute to 1808 indicate that it returns a handle to the internal data of an object, 1809 and that this reference will be invalidated if the object is 1810 destroyed. When such a message is sent to an object, the object's 1811 lifetime will be extended until at least the earliest of:</p> 1812 1813 <ul> 1814 <li>the last use of the returned pointer, or any pointer derived from 1815 it, in the calling function or</li> 1816 <li>the autorelease pool is restored to a previous state.</li> 1817 </ul> 1818 1819 <div class="rationale"><p>Rationale: not all memory and resources are 1820 managed with reference counts; it is common for objects to manage 1821 private resources in their own, private way. Typically these 1822 resources are completely encapsulated within the object, but some 1823 classes offer their users direct access for efficiency. If ARC is not 1824 aware of methods that return such <q>interior</q> pointers, its 1825 optimizations can cause the owning object to be reclaimed too soon. 1826 This attribute informs ARC that it must tread lightly.</p> 1827 1828 <p>The extension rules are somewhat intentionally vague. The 1829 autorelease pool limit is there to permit a simple implementation to 1830 simply retain and autorelease the receiver. The other limit permits 1831 some amount of optimization. The phrase <q>derived from</q> is 1832 intended to encompass the results both of pointer transformations, 1833 such as casts and arithmetic, and of loading from such derived 1834 pointers; furthermore, it applies whether or not such derivations are 1835 applied directly in the calling code or by other utility code (for 1836 example, the C library routine <tt>strchr</tt>). However, the 1837 implementation never need account for uses after a return from the 1838 code which calls the method returning an interior pointer.</p></div> 1839 1840 <p>As an exception, no extension is required if the receiver is loaded 1841 directly from a <tt>__strong</tt> object 1842 with <a href="#optimization.precise">precise lifetime semantics</a>.</p> 1843 1844 <div class="rationale"><p>Rationale: implicit autoreleases carry the 1845 risk of significantly inflating memory use, so it's important to 1846 provide users a way of avoiding these autoreleases. Tying this to 1847 precise lifetime semantics is ideal, as for local variables this 1848 requires a very explicit annotation, which allows ARC to trust the 1849 user with good cheer.</p></div> 1850 1851 </div> <!-- misc.interior --> 1852 1853 <div id="misc.c-retainable"> 1854 <h1>C retainable pointer types</h1> 1855 1856 <p>A type is a <span class="term">C retainable pointer type</span> 1857 if it is a pointer to (possibly qualified) <tt>void</tt> or a 1858 pointer to a (possibly qualifier) <tt>struct</tt> or <tt>class</tt> 1859 type.</p> 1860 1861 <div class="rationale"><p>Rationale: ARC does not manage pointers of 1862 CoreFoundation type (or any of the related families of retainable C 1863 pointers which interoperate with Objective-C for retain/release 1864 operation). In fact, ARC does not even know how to distinguish these 1865 types from arbitrary C pointer types. The intent of this concept is 1866 to filter out some obviously non-object types while leaving a hook for 1867 later tightening if a means of exhaustively marking CF types is made 1868 available.</p></div> 1869 1870 <div id="misc.c-retainable.audit"> 1871 <h1>Auditing of C retainable pointer interfaces</h1> 1872 1873 <p><span class="revision"><span class="whenRevised">[beginning Apple 4.0, LLVM 3.1]</span></span></p> 1874 1875 <p>A C function may be marked with the <tt>cf_audited_transfer</tt> 1876 attribute to express that, except as otherwise marked with attributes, 1877 it obeys the parameter (consuming vs. non-consuming) and return 1878 (retained vs. non-retained) conventions for a C function of its name, 1879 namely:</p> 1880 1881 <ul> 1882 <li>A parameter of C retainable pointer type is assumed to not be 1883 consumed unless it is marked with the <tt>cf_consumed</tt> attribute, and</li> 1884 <li>A result of C retainable pointer type is assumed to not be 1885 returned retained unless the function is either 1886 marked <tt>cf_returns_retained</tt> or it follows 1887 the create/copy naming convention and is not 1888 marked <tt>cf_returns_not_retained</tt>.</li> 1889 </ul> 1890 1891 <p>A function obeys the <span class="term">create/copy</span> naming 1892 convention if its name contains as a substring:</p> 1893 <ul> 1894 <li>either <q>Create</q> or <q>Copy</q> not followed by a lowercase letter, or</li> 1895 <li>either <q>create</q> or <q>copy</q> not followed by a lowercase 1896 letter and not preceded by any letter, whether uppercase or lowercase.</li> 1897 </ul> 1898 1899 <p>A second attribute, <tt>cf_unknown_transfer</tt>, signifies that a 1900 function's transfer semantics cannot be accurately captured using any 1901 of these annotations. A program is ill-formed if it annotates the 1902 same function with both <tt>cf_audited_transfer</tt> 1903 and <tt>cf_unknown_transfer</tt>.</p> 1904 1905 <p>A pragma is provided to facilitate the mass annotation of interfaces:</p> 1906 1907 <pre>#pragma clang arc_cf_code_audited begin 1908 ... 1909 #pragma clang arc_cf_code_audited end</pre> 1910 1911 <p>All C functions declared within the extent of this pragma are 1912 treated as if annotated with the <tt>cf_audited_transfer</tt> 1913 attribute unless they otherwise have the <tt>cf_unknown_transfer</tt> 1914 attribute. The pragma is accepted in all language modes. A program 1915 is ill-formed if it attempts to change files, whether by including a 1916 file or ending the current file, within the extent of this pragma.</p> 1917 1918 <p>It is possible to test for all the features in this section with 1919 <tt>__has_feature(arc_cf_code_audited)</tt>.</p> 1920 1921 <div class="rationale"><p>Rationale: A significant inconvenience in 1922 ARC programming is the necessity of interacting with APIs based around 1923 C retainable pointers. These features are designed to make it 1924 relatively easy for API authors to quickly review and annotate their 1925 interfaces, in turn improving the fidelity of tools such as the static 1926 analyzer and ARC. The single-file restriction on the pragma is 1927 designed to eliminate the risk of accidentally annotating some other 1928 header's interfaces.</p></div> 1929 1930 </div> <!-- misc.c-retainable.audit --> 1931 1932 </div> <!-- misc.c-retainable --> 1933 1934 </div> <!-- misc --> 1935 1936 <div id="runtime"> 1937 <h1>Runtime support</h1> 1938 1939 <p>This section describes the interaction between the ARC runtime and 1940 the code generated by the ARC compiler. This is not part of the ARC 1941 language specification; instead, it is effectively a language-specific 1942 ABI supplement, akin to the <q>Itanium</q> generic ABI for C++.</p> 1943 1944 <p>Ownership qualification does not alter the storage requirements for 1945 objects, except that it is undefined behavior if a <tt>__weak</tt> 1946 object is inadequately aligned for an object of type <tt>id</tt>. The 1947 other qualifiers may be used on explicitly under-aligned memory.</p> 1948 1949 <p>The runtime tracks <tt>__weak</tt> objects which holds non-null 1950 values. It is undefined behavior to direct modify a <tt>__weak</tt> 1951 object which is being tracked by the runtime except through an 1952 <a href="#runtime.objc_storeWeak"><tt>objc_storeWeak</tt></a>, 1953 <a href="#runtime.objc_destroyWeak"><tt>objc_destroyWeak</tt></a>, 1954 or <a href="#runtime.objc_moveWeak"><tt>objc_moveWeak</tt></a> 1955 call.</p> 1956 1957 <p>The runtime must provide a number of new entrypoints which the 1958 compiler may emit, which are described in the remainder of this 1959 section.</p> 1960 1961 <div class="rationale"><p>Rationale: Several of these functions are 1962 semantically equivalent to a message send; we emit calls to C 1963 functions instead because:</p> 1964 <ul> 1965 <li>the machine code to do so is significantly smaller,</li> 1966 <li>it is much easier to recognize the C functions in the ARC optimizer, and</li> 1967 <li>a sufficient sophisticated runtime may be able to avoid the 1968 message send in common cases.</li> 1969 </ul> 1970 1971 <p>Several other of these functions are <q>fused</q> operations which 1972 can be described entirely in terms of other operations. We use the 1973 fused operations primarily as a code-size optimization, although in 1974 some cases there is also a real potential for avoiding redundant 1975 operations in the runtime.</p> 1976 1977 </div> 1978 1979 <div id="runtime.objc_autorelease"> 1980 <h1><tt>id objc_autorelease(id value);</tt></h1> 1981 <p><i>Precondition:</i> <tt>value</tt> is null or a pointer to a 1982 valid object.</p> 1983 <p>If <tt>value</tt> is null, this call has no effect. Otherwise, it 1984 adds the object to the innermost autorelease pool exactly as if the 1985 object had been sent the <tt>autorelease</tt> message.</p> 1986 <p>Always returns <tt>value</tt>.</p> 1987 </div> <!-- runtime.objc_autorelease --> 1988 1989 <div id="runtime.objc_autoreleasePoolPop"> 1990 <h1><tt>void objc_autoreleasePoolPop(void *pool);</tt></h1> 1991 <p><i>Precondition:</i> <tt>pool</tt> is the result of a previous call to 1992 <a href="runtime.objc_autoreleasePoolPush"><tt>objc_autoreleasePoolPush</tt></a> 1993 on the current thread, where neither <tt>pool</tt> nor any enclosing 1994 pool have previously been popped.</p> 1995 <p>Releases all the objects added to the given autorelease pool and 1996 any autorelease pools it encloses, then sets the current autorelease 1997 pool to the pool directly enclosing <tt>pool</tt>.</p> 1998 </div> <!-- runtime.objc_autoreleasePoolPop --> 1999 2000 <div id="runtime.objc_autoreleasePoolPush"> 2001 <h1><tt>void *objc_autoreleasePoolPush(void);</tt></h1> 2002 <p>Creates a new autorelease pool that is enclosed by the current 2003 pool, makes that the current pool, and returns an opaque <q>handle</q> 2004 to it.</p> 2005 2006 <div class="rationale"><p>Rationale: while the interface is described 2007 as an explicit hierarchy of pools, the rules allow the implementation 2008 to just keep a stack of objects, using the stack depth as the opaque 2009 pool handle.</p></div> 2010 2011 </div> <!-- runtime.objc_autoreleasePoolPush --> 2012 2013 <div id="runtime.objc_autoreleaseReturnValue"> 2014 <h1><tt>id objc_autoreleaseReturnValue(id value);</tt></h1> 2015 <p><i>Precondition:</i> <tt>value</tt> is null or a pointer to a 2016 valid object.</p> 2017 <p>If <tt>value</tt> is null, this call has no effect. Otherwise, it 2018 makes a best effort to hand off ownership of a retain count on the 2019 object to a call 2020 to <a href="runtime.objc_retainAutoreleasedReturnValue"><tt>objc_retainAutoreleasedReturnValue</tt></a> 2021 for the same object in an enclosing call frame. If this is not 2022 possible, the object is autoreleased as above.</p> 2023 <p>Always returns <tt>value</tt>.</p> 2024 </div> <!-- runtime.objc_autoreleaseReturnValue --> 2025 2026 <div id="runtime.objc_copyWeak"> 2027 <h1><tt>void objc_copyWeak(id *dest, id *src);</tt></h1> 2028 <p><i>Precondition:</i> <tt>src</tt> is a valid pointer which either 2029 contains a null pointer or has been registered as a <tt>__weak</tt> 2030 object. <tt>dest</tt> is a valid pointer which has not been 2031 registered as a <tt>__weak</tt> object.</p> 2032 <p><tt>dest</tt> is initialized to be equivalent to <tt>src</tt>, 2033 potentially registering it with the runtime. Equivalent to the 2034 following code:</p> 2035 <pre>void objc_copyWeak(id *dest, id *src) { 2036 objc_release(objc_initWeak(dest, objc_loadWeakRetained(src))); 2037 }</pre> 2038 <p>Must be atomic with respect to calls to <tt>objc_storeWeak</tt> 2039 on <tt>src</tt>.</p> 2040 </div> <!-- runtime.objc_copyWeak --> 2041 2042 <div id="runtime.objc_destroyWeak"> 2043 <h1><tt>void objc_destroyWeak(id *object);</tt></h1> 2044 <p><i>Precondition:</i> <tt>object</tt> is a valid pointer which 2045 either contains a null pointer or has been registered as 2046 a <tt>__weak</tt> object.</p> 2047 <p><tt>object</tt> is unregistered as a weak object, if it ever was. 2048 The current value of <tt>object</tt> is left unspecified; otherwise, 2049 equivalent to the following code:</p> 2050 <pre>void objc_destroyWeak(id *object) { 2051 objc_storeWeak(object, nil); 2052 }</pre> 2053 <p>Does not need to be atomic with respect to calls 2054 to <tt>objc_storeWeak</tt> on <tt>object</tt>.</p> 2055 </div> <!-- runtime.objc_destroyWeak --> 2056 2057 <div id="runtime.objc_initWeak"> 2058 <h1><tt>id objc_initWeak(id *object, id value);</tt></h1> 2059 <p><i>Precondition:</i> <tt>object</tt> is a valid pointer which has 2060 not been registered as a <tt>__weak</tt> object. <tt>value</tt> is 2061 null or a pointer to a valid object.</p> 2062 <p>If <tt>value</tt> is a null pointer or the object to which it 2063 points has begun deallocation, <tt>object</tt> is zero-initialized. 2064 Otherwise, <tt>object</tt> is registered as a <tt>__weak</tt> object 2065 pointing to <tt>value</tt>. Equivalent to the following code:</p> 2066 <pre>id objc_initWeak(id *object, id value) { 2067 *object = nil; 2068 return objc_storeWeak(object, value); 2069 }</pre> 2070 <p>Returns the value of <tt>object</tt> after the call.</p> 2071 <p>Does not need to be atomic with respect to calls 2072 to <tt>objc_storeWeak</tt> on <tt>object</tt>.</p> 2073 </div> <!-- runtime.objc_initWeak --> 2074 2075 <div id="runtime.objc_loadWeak"> 2076 <h1><tt>id objc_loadWeak(id *object);</tt></h1> 2077 <p><i>Precondition:</i> <tt>object</tt> is a valid pointer which 2078 either contains a null pointer or has been registered as 2079 a <tt>__weak</tt> object.</p> 2080 <p>If <tt>object</tt> is registered as a <tt>__weak</tt> object, and 2081 the last value stored into <tt>object</tt> has not yet been 2082 deallocated or begun deallocation, retains and autoreleases that value 2083 and returns it. Otherwise returns null. Equivalent to the following 2084 code:</p> 2085 <pre>id objc_loadWeak(id *object) { 2086 return objc_autorelease(objc_loadWeakRetained(object)); 2087 }</pre> 2088 <p>Must be atomic with respect to calls to <tt>objc_storeWeak</tt> 2089 on <tt>object</tt>.</p> 2090 <div class="rationale">Rationale: loading weak references would be 2091 inherently prone to race conditions without the retain.</div> 2092 </div> <!-- runtime.objc_loadWeak --> 2093 2094 <div id="runtime.objc_loadWeakRetained"> 2095 <h1><tt>id objc_loadWeakRetained(id *object);</tt></h1> 2096 <p><i>Precondition:</i> <tt>object</tt> is a valid pointer which 2097 either contains a null pointer or has been registered as 2098 a <tt>__weak</tt> object.</p> 2099 <p>If <tt>object</tt> is registered as a <tt>__weak</tt> object, and 2100 the last value stored into <tt>object</tt> has not yet been 2101 deallocated or begun deallocation, retains that value and returns it. 2102 Otherwise returns null.</p> 2103 <p>Must be atomic with respect to calls to <tt>objc_storeWeak</tt> 2104 on <tt>object</tt>.</p> 2105 </div> <!-- runtime.objc_loadWeakRetained --> 2106 2107 <div id="runtime.objc_moveWeak"> 2108 <h1><tt>void objc_moveWeak(id *dest, id *src);</tt></h1> 2109 <p><i>Precondition:</i> <tt>src</tt> is a valid pointer which either 2110 contains a null pointer or has been registered as a <tt>__weak</tt> 2111 object. <tt>dest</tt> is a valid pointer which has not been 2112 registered as a <tt>__weak</tt> object.</p> 2113 <p><tt>dest</tt> is initialized to be equivalent to <tt>src</tt>, 2114 potentially registering it with the runtime. <tt>src</tt> may then be 2115 left in its original state, in which case this call is equivalent 2116 to <a href="#runtime.objc_copyWeak"><tt>objc_copyWeak</tt></a>, or it 2117 may be left as null.</p> 2118 <p>Must be atomic with respect to calls to <tt>objc_storeWeak</tt> 2119 on <tt>src</tt>.</p> 2120 </div> <!-- runtime.objc_moveWeak --> 2121 2122 <div id="runtime.objc_release"> 2123 <h1><tt>void objc_release(id value);</tt></h1> 2124 <p><i>Precondition:</i> <tt>value</tt> is null or a pointer to a 2125 valid object.</p> 2126 <p>If <tt>value</tt> is null, this call has no effect. Otherwise, it 2127 performs a release operation exactly as if the object had been sent 2128 the <tt>release</tt> message.</p> 2129 </div> <!-- runtime.objc_release --> 2130 2131 <div id="runtime.objc_retain"> 2132 <h1><tt>id objc_retain(id value);</tt></h1> 2133 <p><i>Precondition:</i> <tt>value</tt> is null or a pointer to a 2134 valid object.</p> 2135 <p>If <tt>value</tt> is null, this call has no effect. Otherwise, it 2136 performs a retain operation exactly as if the object had been sent 2137 the <tt>retain</tt> message.</p> 2138 <p>Always returns <tt>value</tt>.</p> 2139 </div> <!-- runtime.objc_retain --> 2140 2141 <div id="runtime.objc_retainAutorelease"> 2142 <h1><tt>id objc_retainAutorelease(id value);</tt></h1> 2143 <p><i>Precondition:</i> <tt>value</tt> is null or a pointer to a 2144 valid object.</p> 2145 <p>If <tt>value</tt> is null, this call has no effect. Otherwise, it 2146 performs a retain operation followed by an autorelease operation. 2147 Equivalent to the following code:</p> 2148 <pre>id objc_retainAutorelease(id value) { 2149 return objc_autorelease(objc_retain(value)); 2150 }</pre> 2151 <p>Always returns <tt>value</tt>.</p> 2152 </div> <!-- runtime.objc_retainAutorelease --> 2153 2154 <div id="runtime.objc_retainAutoreleaseReturnValue"> 2155 <h1><tt>id objc_retainAutoreleaseReturnValue(id value);</tt></h1> 2156 <p><i>Precondition:</i> <tt>value</tt> is null or a pointer to a 2157 valid object.</p> 2158 <p>If <tt>value</tt> is null, this call has no effect. Otherwise, it 2159 performs a retain operation followed by the operation described in 2160 <a href="#runtime.objc_autoreleaseReturnValue"><tt>objc_autoreleaseReturnValue</tt></a>. 2161 Equivalent to the following code:</p> 2162 <pre>id objc_retainAutoreleaseReturnValue(id value) { 2163 return objc_autoreleaseReturnValue(objc_retain(value)); 2164 }</pre> 2165 <p>Always returns <tt>value</tt>.</p> 2166 </div> <!-- runtime.objc_retainAutoreleaseReturnValue --> 2167 2168 <div id="runtime.objc_retainAutoreleasedReturnValue"> 2169 <h1><tt>id objc_retainAutoreleasedReturnValue(id value);</tt></h1> 2170 <p><i>Precondition:</i> <tt>value</tt> is null or a pointer to a 2171 valid object.</p> 2172 <p>If <tt>value</tt> is null, this call has no effect. Otherwise, it 2173 attempts to accept a hand off of a retain count from a call to 2174 <a href="#runtime.objc_autoreleaseReturnValue"><tt>objc_autoreleaseReturnValue</tt></a> 2175 on <tt>value</tt> in a recently-called function or something it 2176 calls. If that fails, it performs a retain operation exactly 2177 like <a href="#runtime.objc_retain"><tt>objc_retain</tt></a>.</p> 2178 <p>Always returns <tt>value</tt>.</p> 2179 </div> <!-- runtime.objc_retainAutoreleasedReturnValue --> 2180 2181 <div id="runtime.objc_retainBlock"> 2182 <h1><tt>id objc_retainBlock(id value);</tt></h1> 2183 <p><i>Precondition:</i> <tt>value</tt> is null or a pointer to a 2184 valid block object.</p> 2185 <p>If <tt>value</tt> is null, this call has no effect. Otherwise, if 2186 the block pointed to by <tt>value</tt> is still on the stack, it is 2187 copied to the heap and the address of the copy is returned. Otherwise 2188 a retain operation is performed on the block exactly as if it had been 2189 sent the <tt>retain</tt> message.</p> 2190 </div> <!-- runtime.objc_retainBlock --> 2191 2192 <div id="runtime.objc_storeStrong"> 2193 <h1><tt>id objc_storeStrong(id *object, id value);</tt></h1> 2194 <p><i>Precondition:</i> <tt>object</tt> is a valid pointer to 2195 a <tt>__strong</tt> object which is adequately aligned for a 2196 pointer. <tt>value</tt> is null or a pointer to a valid object.</p> 2197 <p>Performs the complete sequence for assigning to a <tt>__strong</tt> 2198 object of non-block type. Equivalent to the following code:</p> 2199 <pre>id objc_storeStrong(id *object, id value) { 2200 value = [value retain]; 2201 id oldValue = *object; 2202 *object = value; 2203 [oldValue release]; 2204 return value; 2205 }</pre> 2206 <p>Always returns <tt>value</tt>.</p> 2207 </div> <!-- runtime.objc_storeStrong --> 2208 2209 <div id="runtime.objc_storeWeak"> 2210 <h1><tt>id objc_storeWeak(id *object, id value);</tt></h1> 2211 <p><i>Precondition:</i> <tt>object</tt> is a valid pointer which 2212 either contains a null pointer or has been registered as 2213 a <tt>__weak</tt> object. <tt>value</tt> is null or a pointer to a 2214 valid object.</p> 2215 <p>If <tt>value</tt> is a null pointer or the object to which it 2216 points has begun deallocation, <tt>object</tt> is assigned null 2217 and unregistered as a <tt>__weak</tt> object. Otherwise, 2218 <tt>object</tt> is registered as a <tt>__weak</tt> object or has its 2219 registration updated to point to <tt>value</tt>.</p> 2220 <p>Returns the value of <tt>object</tt> after the call.</p> 2221 </div> <!-- runtime.objc_storeWeak --> 2222 2223 </div> <!-- runtime --> 2224 </div> <!-- root --> 2225 </body> 2226 </html> 2227