AutomaticReferenceCounting.rst 103 KB

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