objc.texi 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211
  1. @c Copyright (C) 1988-2015 Free Software Foundation, Inc.
  2. @c This is part of the GCC manual.
  3. @c For copying conditions, see the file gcc.texi.
  4. @node Objective-C
  5. @comment node-name, next, previous, up
  6. @chapter GNU Objective-C Features
  7. This document is meant to describe some of the GNU Objective-C
  8. features. It is not intended to teach you Objective-C. There are
  9. several resources on the Internet that present the language.
  10. @menu
  11. * GNU Objective-C runtime API::
  12. * Executing code before main::
  13. * Type encoding::
  14. * Garbage Collection::
  15. * Constant string objects::
  16. * compatibility_alias::
  17. * Exceptions::
  18. * Synchronization::
  19. * Fast enumeration::
  20. * Messaging with the GNU Objective-C runtime::
  21. @end menu
  22. @c =========================================================================
  23. @node GNU Objective-C runtime API
  24. @section GNU Objective-C Runtime API
  25. This section is specific for the GNU Objective-C runtime. If you are
  26. using a different runtime, you can skip it.
  27. The GNU Objective-C runtime provides an API that allows you to
  28. interact with the Objective-C runtime system, querying the live
  29. runtime structures and even manipulating them. This allows you for
  30. example to inspect and navigate classes, methods and protocols; to
  31. define new classes or new methods, and even to modify existing classes
  32. or protocols.
  33. If you are using a ``Foundation'' library such as GNUstep-Base, this
  34. library will provide you with a rich set of functionality to do most
  35. of the inspection tasks, and you probably will only need direct access
  36. to the GNU Objective-C runtime API to define new classes or methods.
  37. @menu
  38. * Modern GNU Objective-C runtime API::
  39. * Traditional GNU Objective-C runtime API::
  40. @end menu
  41. @c =========================================================================
  42. @node Modern GNU Objective-C runtime API
  43. @subsection Modern GNU Objective-C Runtime API
  44. The GNU Objective-C runtime provides an API which is similar to the
  45. one provided by the ``Objective-C 2.0'' Apple/NeXT Objective-C
  46. runtime. The API is documented in the public header files of the GNU
  47. Objective-C runtime:
  48. @itemize @bullet
  49. @item
  50. @file{objc/objc.h}: this is the basic Objective-C header file,
  51. defining the basic Objective-C types such as @code{id}, @code{Class}
  52. and @code{BOOL}. You have to include this header to do almost
  53. anything with Objective-C.
  54. @item
  55. @file{objc/runtime.h}: this header declares most of the public runtime
  56. API functions allowing you to inspect and manipulate the Objective-C
  57. runtime data structures. These functions are fairly standardized
  58. across Objective-C runtimes and are almost identical to the Apple/NeXT
  59. Objective-C runtime ones. It does not declare functions in some
  60. specialized areas (constructing and forwarding message invocations,
  61. threading) which are in the other headers below. You have to include
  62. @file{objc/objc.h} and @file{objc/runtime.h} to use any of the
  63. functions, such as @code{class_getName()}, declared in
  64. @file{objc/runtime.h}.
  65. @item
  66. @file{objc/message.h}: this header declares public functions used to
  67. construct, deconstruct and forward message invocations. Because
  68. messaging is done in quite a different way on different runtimes,
  69. functions in this header are specific to the GNU Objective-C runtime
  70. implementation.
  71. @item
  72. @file{objc/objc-exception.h}: this header declares some public
  73. functions related to Objective-C exceptions. For example functions in
  74. this header allow you to throw an Objective-C exception from plain
  75. C/C++ code.
  76. @item
  77. @file{objc/objc-sync.h}: this header declares some public functions
  78. related to the Objective-C @code{@@synchronized()} syntax, allowing
  79. you to emulate an Objective-C @code{@@synchronized()} block in plain
  80. C/C++ code.
  81. @item
  82. @file{objc/thr.h}: this header declares a public runtime API threading
  83. layer that is only provided by the GNU Objective-C runtime. It
  84. declares functions such as @code{objc_mutex_lock()}, which provide a
  85. platform-independent set of threading functions.
  86. @end itemize
  87. The header files contain detailed documentation for each function in
  88. the GNU Objective-C runtime API.
  89. @c =========================================================================
  90. @node Traditional GNU Objective-C runtime API
  91. @subsection Traditional GNU Objective-C Runtime API
  92. The GNU Objective-C runtime used to provide a different API, which we
  93. call the ``traditional'' GNU Objective-C runtime API. Functions
  94. belonging to this API are easy to recognize because they use a
  95. different naming convention, such as @code{class_get_super_class()}
  96. (traditional API) instead of @code{class_getSuperclass()} (modern
  97. API). Software using this API includes the file
  98. @file{objc/objc-api.h} where it is declared.
  99. Starting with GCC 4.7.0, the traditional GNU runtime API is no longer
  100. available.
  101. @c =========================================================================
  102. @node Executing code before main
  103. @section @code{+load}: Executing Code before @code{main}
  104. This section is specific for the GNU Objective-C runtime. If you are
  105. using a different runtime, you can skip it.
  106. The GNU Objective-C runtime provides a way that allows you to execute
  107. code before the execution of the program enters the @code{main}
  108. function. The code is executed on a per-class and a per-category basis,
  109. through a special class method @code{+load}.
  110. This facility is very useful if you want to initialize global variables
  111. which can be accessed by the program directly, without sending a message
  112. to the class first. The usual way to initialize global variables, in the
  113. @code{+initialize} method, might not be useful because
  114. @code{+initialize} is only called when the first message is sent to a
  115. class object, which in some cases could be too late.
  116. Suppose for example you have a @code{FileStream} class that declares
  117. @code{Stdin}, @code{Stdout} and @code{Stderr} as global variables, like
  118. below:
  119. @smallexample
  120. FileStream *Stdin = nil;
  121. FileStream *Stdout = nil;
  122. FileStream *Stderr = nil;
  123. @@implementation FileStream
  124. + (void)initialize
  125. @{
  126. Stdin = [[FileStream new] initWithFd:0];
  127. Stdout = [[FileStream new] initWithFd:1];
  128. Stderr = [[FileStream new] initWithFd:2];
  129. @}
  130. /* @r{Other methods here} */
  131. @@end
  132. @end smallexample
  133. In this example, the initialization of @code{Stdin}, @code{Stdout} and
  134. @code{Stderr} in @code{+initialize} occurs too late. The programmer can
  135. send a message to one of these objects before the variables are actually
  136. initialized, thus sending messages to the @code{nil} object. The
  137. @code{+initialize} method which actually initializes the global
  138. variables is not invoked until the first message is sent to the class
  139. object. The solution would require these variables to be initialized
  140. just before entering @code{main}.
  141. The correct solution of the above problem is to use the @code{+load}
  142. method instead of @code{+initialize}:
  143. @smallexample
  144. @@implementation FileStream
  145. + (void)load
  146. @{
  147. Stdin = [[FileStream new] initWithFd:0];
  148. Stdout = [[FileStream new] initWithFd:1];
  149. Stderr = [[FileStream new] initWithFd:2];
  150. @}
  151. /* @r{Other methods here} */
  152. @@end
  153. @end smallexample
  154. The @code{+load} is a method that is not overridden by categories. If a
  155. class and a category of it both implement @code{+load}, both methods are
  156. invoked. This allows some additional initializations to be performed in
  157. a category.
  158. This mechanism is not intended to be a replacement for @code{+initialize}.
  159. You should be aware of its limitations when you decide to use it
  160. instead of @code{+initialize}.
  161. @menu
  162. * What you can and what you cannot do in +load::
  163. @end menu
  164. @node What you can and what you cannot do in +load
  165. @subsection What You Can and Cannot Do in @code{+load}
  166. @code{+load} is to be used only as a last resort. Because it is
  167. executed very early, most of the Objective-C runtime machinery will
  168. not be ready when @code{+load} is executed; hence @code{+load} works
  169. best for executing C code that is independent on the Objective-C
  170. runtime.
  171. The @code{+load} implementation in the GNU runtime guarantees you the
  172. following things:
  173. @itemize @bullet
  174. @item
  175. you can write whatever C code you like;
  176. @item
  177. you can allocate and send messages to objects whose class is implemented
  178. in the same file;
  179. @item
  180. the @code{+load} implementation of all super classes of a class are
  181. executed before the @code{+load} of that class is executed;
  182. @item
  183. the @code{+load} implementation of a class is executed before the
  184. @code{+load} implementation of any category.
  185. @end itemize
  186. In particular, the following things, even if they can work in a
  187. particular case, are not guaranteed:
  188. @itemize @bullet
  189. @item
  190. allocation of or sending messages to arbitrary objects;
  191. @item
  192. allocation of or sending messages to objects whose classes have a
  193. category implemented in the same file;
  194. @item
  195. sending messages to Objective-C constant strings (@code{@@"this is a
  196. constant string"});
  197. @end itemize
  198. You should make no assumptions about receiving @code{+load} in sibling
  199. classes when you write @code{+load} of a class. The order in which
  200. sibling classes receive @code{+load} is not guaranteed.
  201. The order in which @code{+load} and @code{+initialize} are called could
  202. be problematic if this matters. If you don't allocate objects inside
  203. @code{+load}, it is guaranteed that @code{+load} is called before
  204. @code{+initialize}. If you create an object inside @code{+load} the
  205. @code{+initialize} method of object's class is invoked even if
  206. @code{+load} was not invoked. Note if you explicitly call @code{+load}
  207. on a class, @code{+initialize} will be called first. To avoid possible
  208. problems try to implement only one of these methods.
  209. The @code{+load} method is also invoked when a bundle is dynamically
  210. loaded into your running program. This happens automatically without any
  211. intervening operation from you. When you write bundles and you need to
  212. write @code{+load} you can safely create and send messages to objects whose
  213. classes already exist in the running program. The same restrictions as
  214. above apply to classes defined in bundle.
  215. @node Type encoding
  216. @section Type Encoding
  217. This is an advanced section. Type encodings are used extensively by
  218. the compiler and by the runtime, but you generally do not need to know
  219. about them to use Objective-C.
  220. The Objective-C compiler generates type encodings for all the types.
  221. These type encodings are used at runtime to find out information about
  222. selectors and methods and about objects and classes.
  223. The types are encoded in the following way:
  224. @c @sp 1
  225. @multitable @columnfractions .25 .75
  226. @item @code{_Bool}
  227. @tab @code{B}
  228. @item @code{char}
  229. @tab @code{c}
  230. @item @code{unsigned char}
  231. @tab @code{C}
  232. @item @code{short}
  233. @tab @code{s}
  234. @item @code{unsigned short}
  235. @tab @code{S}
  236. @item @code{int}
  237. @tab @code{i}
  238. @item @code{unsigned int}
  239. @tab @code{I}
  240. @item @code{long}
  241. @tab @code{l}
  242. @item @code{unsigned long}
  243. @tab @code{L}
  244. @item @code{long long}
  245. @tab @code{q}
  246. @item @code{unsigned long long}
  247. @tab @code{Q}
  248. @item @code{float}
  249. @tab @code{f}
  250. @item @code{double}
  251. @tab @code{d}
  252. @item @code{long double}
  253. @tab @code{D}
  254. @item @code{void}
  255. @tab @code{v}
  256. @item @code{id}
  257. @tab @code{@@}
  258. @item @code{Class}
  259. @tab @code{#}
  260. @item @code{SEL}
  261. @tab @code{:}
  262. @item @code{char*}
  263. @tab @code{*}
  264. @item @code{enum}
  265. @tab an @code{enum} is encoded exactly as the integer type that the compiler uses for it, which depends on the enumeration
  266. values. Often the compiler users @code{unsigned int}, which is then encoded as @code{I}.
  267. @item unknown type
  268. @tab @code{?}
  269. @item Complex types
  270. @tab @code{j} followed by the inner type. For example @code{_Complex double} is encoded as "jd".
  271. @item bit-fields
  272. @tab @code{b} followed by the starting position of the bit-field, the type of the bit-field and the size of the bit-field (the bit-fields encoding was changed from the NeXT's compiler encoding, see below)
  273. @end multitable
  274. @c @sp 1
  275. The encoding of bit-fields has changed to allow bit-fields to be
  276. properly handled by the runtime functions that compute sizes and
  277. alignments of types that contain bit-fields. The previous encoding
  278. contained only the size of the bit-field. Using only this information
  279. it is not possible to reliably compute the size occupied by the
  280. bit-field. This is very important in the presence of the Boehm's
  281. garbage collector because the objects are allocated using the typed
  282. memory facility available in this collector. The typed memory
  283. allocation requires information about where the pointers are located
  284. inside the object.
  285. The position in the bit-field is the position, counting in bits, of the
  286. bit closest to the beginning of the structure.
  287. The non-atomic types are encoded as follows:
  288. @c @sp 1
  289. @multitable @columnfractions .2 .8
  290. @item pointers
  291. @tab @samp{^} followed by the pointed type.
  292. @item arrays
  293. @tab @samp{[} followed by the number of elements in the array followed by the type of the elements followed by @samp{]}
  294. @item structures
  295. @tab @samp{@{} followed by the name of the structure (or @samp{?} if the structure is unnamed), the @samp{=} sign, the type of the members and by @samp{@}}
  296. @item unions
  297. @tab @samp{(} followed by the name of the structure (or @samp{?} if the union is unnamed), the @samp{=} sign, the type of the members followed by @samp{)}
  298. @item vectors
  299. @tab @samp{![} followed by the vector_size (the number of bytes composing the vector) followed by a comma, followed by the alignment (in bytes) of the vector, followed by the type of the elements followed by @samp{]}
  300. @end multitable
  301. Here are some types and their encodings, as they are generated by the
  302. compiler on an i386 machine:
  303. @sp 1
  304. @multitable @columnfractions .25 .75
  305. @item Objective-C type
  306. @tab Compiler encoding
  307. @item
  308. @smallexample
  309. int a[10];
  310. @end smallexample
  311. @tab @code{[10i]}
  312. @item
  313. @smallexample
  314. struct @{
  315. int i;
  316. float f[3];
  317. int a:3;
  318. int b:2;
  319. char c;
  320. @}
  321. @end smallexample
  322. @tab @code{@{?=i[3f]b128i3b131i2c@}}
  323. @item
  324. @smallexample
  325. int a __attribute__ ((vector_size (16)));
  326. @end smallexample
  327. @tab @code{![16,16i]} (alignment would depend on the machine)
  328. @end multitable
  329. @sp 1
  330. In addition to the types the compiler also encodes the type
  331. specifiers. The table below describes the encoding of the current
  332. Objective-C type specifiers:
  333. @sp 1
  334. @multitable @columnfractions .25 .75
  335. @item Specifier
  336. @tab Encoding
  337. @item @code{const}
  338. @tab @code{r}
  339. @item @code{in}
  340. @tab @code{n}
  341. @item @code{inout}
  342. @tab @code{N}
  343. @item @code{out}
  344. @tab @code{o}
  345. @item @code{bycopy}
  346. @tab @code{O}
  347. @item @code{byref}
  348. @tab @code{R}
  349. @item @code{oneway}
  350. @tab @code{V}
  351. @end multitable
  352. @sp 1
  353. The type specifiers are encoded just before the type. Unlike types
  354. however, the type specifiers are only encoded when they appear in method
  355. argument types.
  356. Note how @code{const} interacts with pointers:
  357. @sp 1
  358. @multitable @columnfractions .25 .75
  359. @item Objective-C type
  360. @tab Compiler encoding
  361. @item
  362. @smallexample
  363. const int
  364. @end smallexample
  365. @tab @code{ri}
  366. @item
  367. @smallexample
  368. const int*
  369. @end smallexample
  370. @tab @code{^ri}
  371. @item
  372. @smallexample
  373. int *const
  374. @end smallexample
  375. @tab @code{r^i}
  376. @end multitable
  377. @sp 1
  378. @code{const int*} is a pointer to a @code{const int}, and so is
  379. encoded as @code{^ri}. @code{int* const}, instead, is a @code{const}
  380. pointer to an @code{int}, and so is encoded as @code{r^i}.
  381. Finally, there is a complication when encoding @code{const char *}
  382. versus @code{char * const}. Because @code{char *} is encoded as
  383. @code{*} and not as @code{^c}, there is no way to express the fact
  384. that @code{r} applies to the pointer or to the pointee.
  385. Hence, it is assumed as a convention that @code{r*} means @code{const
  386. char *} (since it is what is most often meant), and there is no way to
  387. encode @code{char *const}. @code{char *const} would simply be encoded
  388. as @code{*}, and the @code{const} is lost.
  389. @menu
  390. * Legacy type encoding::
  391. * @@encode::
  392. * Method signatures::
  393. @end menu
  394. @node Legacy type encoding
  395. @subsection Legacy Type Encoding
  396. Unfortunately, historically GCC used to have a number of bugs in its
  397. encoding code. The NeXT runtime expects GCC to emit type encodings in
  398. this historical format (compatible with GCC-3.3), so when using the
  399. NeXT runtime, GCC will introduce on purpose a number of incorrect
  400. encodings:
  401. @itemize @bullet
  402. @item
  403. the read-only qualifier of the pointee gets emitted before the '^'.
  404. The read-only qualifier of the pointer itself gets ignored, unless it
  405. is a typedef. Also, the 'r' is only emitted for the outermost type.
  406. @item
  407. 32-bit longs are encoded as 'l' or 'L', but not always. For typedefs,
  408. the compiler uses 'i' or 'I' instead if encoding a struct field or a
  409. pointer.
  410. @item
  411. @code{enum}s are always encoded as 'i' (int) even if they are actually
  412. unsigned or long.
  413. @end itemize
  414. In addition to that, the NeXT runtime uses a different encoding for
  415. bitfields. It encodes them as @code{b} followed by the size, without
  416. a bit offset or the underlying field type.
  417. @node @@encode
  418. @subsection @code{@@encode}
  419. GNU Objective-C supports the @code{@@encode} syntax that allows you to
  420. create a type encoding from a C/Objective-C type. For example,
  421. @code{@@encode(int)} is compiled by the compiler into @code{"i"}.
  422. @code{@@encode} does not support type qualifiers other than
  423. @code{const}. For example, @code{@@encode(const char*)} is valid and
  424. is compiled into @code{"r*"}, while @code{@@encode(bycopy char *)} is
  425. invalid and will cause a compilation error.
  426. @node Method signatures
  427. @subsection Method Signatures
  428. This section documents the encoding of method types, which is rarely
  429. needed to use Objective-C. You should skip it at a first reading; the
  430. runtime provides functions that will work on methods and can walk
  431. through the list of parameters and interpret them for you. These
  432. functions are part of the public ``API'' and are the preferred way to
  433. interact with method signatures from user code.
  434. But if you need to debug a problem with method signatures and need to
  435. know how they are implemented (i.e., the ``ABI''), read on.
  436. Methods have their ``signature'' encoded and made available to the
  437. runtime. The ``signature'' encodes all the information required to
  438. dynamically build invocations of the method at runtime: return type
  439. and arguments.
  440. The ``signature'' is a null-terminated string, composed of the following:
  441. @itemize @bullet
  442. @item
  443. The return type, including type qualifiers. For example, a method
  444. returning @code{int} would have @code{i} here.
  445. @item
  446. The total size (in bytes) required to pass all the parameters. This
  447. includes the two hidden parameters (the object @code{self} and the
  448. method selector @code{_cmd}).
  449. @item
  450. Each argument, with the type encoding, followed by the offset (in
  451. bytes) of the argument in the list of parameters.
  452. @end itemize
  453. For example, a method with no arguments and returning @code{int} would
  454. have the signature @code{i8@@0:4} if the size of a pointer is 4. The
  455. signature is interpreted as follows: the @code{i} is the return type
  456. (an @code{int}), the @code{8} is the total size of the parameters in
  457. bytes (two pointers each of size 4), the @code{@@0} is the first
  458. parameter (an object at byte offset @code{0}) and @code{:4} is the
  459. second parameter (a @code{SEL} at byte offset @code{4}).
  460. You can easily find more examples by running the ``strings'' program
  461. on an Objective-C object file compiled by GCC. You'll see a lot of
  462. strings that look very much like @code{i8@@0:4}. They are signatures
  463. of Objective-C methods.
  464. @node Garbage Collection
  465. @section Garbage Collection
  466. This section is specific for the GNU Objective-C runtime. If you are
  467. using a different runtime, you can skip it.
  468. Support for garbage collection with the GNU runtime has been added by
  469. using a powerful conservative garbage collector, known as the
  470. Boehm-Demers-Weiser conservative garbage collector.
  471. To enable the support for it you have to configure the compiler using
  472. an additional argument, @w{@option{--enable-objc-gc}}. This will
  473. build the boehm-gc library, and build an additional runtime library
  474. which has several enhancements to support the garbage collector. The
  475. new library has a new name, @file{libobjc_gc.a} to not conflict with
  476. the non-garbage-collected library.
  477. When the garbage collector is used, the objects are allocated using the
  478. so-called typed memory allocation mechanism available in the
  479. Boehm-Demers-Weiser collector. This mode requires precise information on
  480. where pointers are located inside objects. This information is computed
  481. once per class, immediately after the class has been initialized.
  482. There is a new runtime function @code{class_ivar_set_gcinvisible()}
  483. which can be used to declare a so-called @dfn{weak pointer}
  484. reference. Such a pointer is basically hidden for the garbage collector;
  485. this can be useful in certain situations, especially when you want to
  486. keep track of the allocated objects, yet allow them to be
  487. collected. This kind of pointers can only be members of objects, you
  488. cannot declare a global pointer as a weak reference. Every type which is
  489. a pointer type can be declared a weak pointer, including @code{id},
  490. @code{Class} and @code{SEL}.
  491. Here is an example of how to use this feature. Suppose you want to
  492. implement a class whose instances hold a weak pointer reference; the
  493. following class does this:
  494. @smallexample
  495. @@interface WeakPointer : Object
  496. @{
  497. const void* weakPointer;
  498. @}
  499. - initWithPointer:(const void*)p;
  500. - (const void*)weakPointer;
  501. @@end
  502. @@implementation WeakPointer
  503. + (void)initialize
  504. @{
  505. if (self == objc_lookUpClass ("WeakPointer"))
  506. class_ivar_set_gcinvisible (self, "weakPointer", YES);
  507. @}
  508. - initWithPointer:(const void*)p
  509. @{
  510. weakPointer = p;
  511. return self;
  512. @}
  513. - (const void*)weakPointer
  514. @{
  515. return weakPointer;
  516. @}
  517. @@end
  518. @end smallexample
  519. Weak pointers are supported through a new type character specifier
  520. represented by the @samp{!} character. The
  521. @code{class_ivar_set_gcinvisible()} function adds or removes this
  522. specifier to the string type description of the instance variable named
  523. as argument.
  524. @c =========================================================================
  525. @node Constant string objects
  526. @section Constant String Objects
  527. GNU Objective-C provides constant string objects that are generated
  528. directly by the compiler. You declare a constant string object by
  529. prefixing a C constant string with the character @samp{@@}:
  530. @smallexample
  531. id myString = @@"this is a constant string object";
  532. @end smallexample
  533. The constant string objects are by default instances of the
  534. @code{NXConstantString} class which is provided by the GNU Objective-C
  535. runtime. To get the definition of this class you must include the
  536. @file{objc/NXConstStr.h} header file.
  537. User defined libraries may want to implement their own constant string
  538. class. To be able to support them, the GNU Objective-C compiler provides
  539. a new command line options @option{-fconstant-string-class=@var{class-name}}.
  540. The provided class should adhere to a strict structure, the same
  541. as @code{NXConstantString}'s structure:
  542. @smallexample
  543. @@interface MyConstantStringClass
  544. @{
  545. Class isa;
  546. char *c_string;
  547. unsigned int len;
  548. @}
  549. @@end
  550. @end smallexample
  551. @code{NXConstantString} inherits from @code{Object}; user class
  552. libraries may choose to inherit the customized constant string class
  553. from a different class than @code{Object}. There is no requirement in
  554. the methods the constant string class has to implement, but the final
  555. ivar layout of the class must be the compatible with the given
  556. structure.
  557. When the compiler creates the statically allocated constant string
  558. object, the @code{c_string} field will be filled by the compiler with
  559. the string; the @code{length} field will be filled by the compiler with
  560. the string length; the @code{isa} pointer will be filled with
  561. @code{NULL} by the compiler, and it will later be fixed up automatically
  562. at runtime by the GNU Objective-C runtime library to point to the class
  563. which was set by the @option{-fconstant-string-class} option when the
  564. object file is loaded (if you wonder how it works behind the scenes, the
  565. name of the class to use, and the list of static objects to fixup, are
  566. stored by the compiler in the object file in a place where the GNU
  567. runtime library will find them at runtime).
  568. As a result, when a file is compiled with the
  569. @option{-fconstant-string-class} option, all the constant string objects
  570. will be instances of the class specified as argument to this option. It
  571. is possible to have multiple compilation units referring to different
  572. constant string classes, neither the compiler nor the linker impose any
  573. restrictions in doing this.
  574. @c =========================================================================
  575. @node compatibility_alias
  576. @section @code{compatibility_alias}
  577. The keyword @code{@@compatibility_alias} allows you to define a class name
  578. as equivalent to another class name. For example:
  579. @smallexample
  580. @@compatibility_alias WOApplication GSWApplication;
  581. @end smallexample
  582. tells the compiler that each time it encounters @code{WOApplication} as
  583. a class name, it should replace it with @code{GSWApplication} (that is,
  584. @code{WOApplication} is just an alias for @code{GSWApplication}).
  585. There are some constraints on how this can be used---
  586. @itemize @bullet
  587. @item @code{WOApplication} (the alias) must not be an existing class;
  588. @item @code{GSWApplication} (the real class) must be an existing class.
  589. @end itemize
  590. @c =========================================================================
  591. @node Exceptions
  592. @section Exceptions
  593. GNU Objective-C provides exception support built into the language, as
  594. in the following example:
  595. @smallexample
  596. @@try @{
  597. @dots{}
  598. @@throw expr;
  599. @dots{}
  600. @}
  601. @@catch (AnObjCClass *exc) @{
  602. @dots{}
  603. @@throw expr;
  604. @dots{}
  605. @@throw;
  606. @dots{}
  607. @}
  608. @@catch (AnotherClass *exc) @{
  609. @dots{}
  610. @}
  611. @@catch (id allOthers) @{
  612. @dots{}
  613. @}
  614. @@finally @{
  615. @dots{}
  616. @@throw expr;
  617. @dots{}
  618. @}
  619. @end smallexample
  620. The @code{@@throw} statement may appear anywhere in an Objective-C or
  621. Objective-C++ program; when used inside of a @code{@@catch} block, the
  622. @code{@@throw} may appear without an argument (as shown above), in
  623. which case the object caught by the @code{@@catch} will be rethrown.
  624. Note that only (pointers to) Objective-C objects may be thrown and
  625. caught using this scheme. When an object is thrown, it will be caught
  626. by the nearest @code{@@catch} clause capable of handling objects of
  627. that type, analogously to how @code{catch} blocks work in C++ and
  628. Java. A @code{@@catch(id @dots{})} clause (as shown above) may also
  629. be provided to catch any and all Objective-C exceptions not caught by
  630. previous @code{@@catch} clauses (if any).
  631. The @code{@@finally} clause, if present, will be executed upon exit
  632. from the immediately preceding @code{@@try @dots{} @@catch} section.
  633. This will happen regardless of whether any exceptions are thrown,
  634. caught or rethrown inside the @code{@@try @dots{} @@catch} section,
  635. analogously to the behavior of the @code{finally} clause in Java.
  636. There are several caveats to using the new exception mechanism:
  637. @itemize @bullet
  638. @item
  639. The @option{-fobjc-exceptions} command line option must be used when
  640. compiling Objective-C files that use exceptions.
  641. @item
  642. With the GNU runtime, exceptions are always implemented as ``native''
  643. exceptions and it is recommended that the @option{-fexceptions} and
  644. @option{-shared-libgcc} options are used when linking.
  645. @item
  646. With the NeXT runtime, although currently designed to be binary
  647. compatible with @code{NS_HANDLER}-style idioms provided by the
  648. @code{NSException} class, the new exceptions can only be used on Mac
  649. OS X 10.3 (Panther) and later systems, due to additional functionality
  650. needed in the NeXT Objective-C runtime.
  651. @item
  652. As mentioned above, the new exceptions do not support handling
  653. types other than Objective-C objects. Furthermore, when used from
  654. Objective-C++, the Objective-C exception model does not interoperate with C++
  655. exceptions at this time. This means you cannot @code{@@throw} an exception
  656. from Objective-C and @code{catch} it in C++, or vice versa
  657. (i.e., @code{throw @dots{} @@catch}).
  658. @end itemize
  659. @c =========================================================================
  660. @node Synchronization
  661. @section Synchronization
  662. GNU Objective-C provides support for synchronized blocks:
  663. @smallexample
  664. @@synchronized (ObjCClass *guard) @{
  665. @dots{}
  666. @}
  667. @end smallexample
  668. Upon entering the @code{@@synchronized} block, a thread of execution
  669. shall first check whether a lock has been placed on the corresponding
  670. @code{guard} object by another thread. If it has, the current thread
  671. shall wait until the other thread relinquishes its lock. Once
  672. @code{guard} becomes available, the current thread will place its own
  673. lock on it, execute the code contained in the @code{@@synchronized}
  674. block, and finally relinquish the lock (thereby making @code{guard}
  675. available to other threads).
  676. Unlike Java, Objective-C does not allow for entire methods to be
  677. marked @code{@@synchronized}. Note that throwing exceptions out of
  678. @code{@@synchronized} blocks is allowed, and will cause the guarding
  679. object to be unlocked properly.
  680. Because of the interactions between synchronization and exception
  681. handling, you can only use @code{@@synchronized} when compiling with
  682. exceptions enabled, that is with the command line option
  683. @option{-fobjc-exceptions}.
  684. @c =========================================================================
  685. @node Fast enumeration
  686. @section Fast Enumeration
  687. @menu
  688. * Using fast enumeration::
  689. * c99-like fast enumeration syntax::
  690. * Fast enumeration details::
  691. * Fast enumeration protocol::
  692. @end menu
  693. @c ================================
  694. @node Using fast enumeration
  695. @subsection Using Fast Enumeration
  696. GNU Objective-C provides support for the fast enumeration syntax:
  697. @smallexample
  698. id array = @dots{};
  699. id object;
  700. for (object in array)
  701. @{
  702. /* Do something with 'object' */
  703. @}
  704. @end smallexample
  705. @code{array} needs to be an Objective-C object (usually a collection
  706. object, for example an array, a dictionary or a set) which implements
  707. the ``Fast Enumeration Protocol'' (see below). If you are using a
  708. Foundation library such as GNUstep Base or Apple Cocoa Foundation, all
  709. collection objects in the library implement this protocol and can be
  710. used in this way.
  711. The code above would iterate over all objects in @code{array}. For
  712. each of them, it assigns it to @code{object}, then executes the
  713. @code{Do something with 'object'} statements.
  714. Here is a fully worked-out example using a Foundation library (which
  715. provides the implementation of @code{NSArray}, @code{NSString} and
  716. @code{NSLog}):
  717. @smallexample
  718. NSArray *array = [NSArray arrayWithObjects: @@"1", @@"2", @@"3", nil];
  719. NSString *object;
  720. for (object in array)
  721. NSLog (@@"Iterating over %@@", object);
  722. @end smallexample
  723. @c ================================
  724. @node c99-like fast enumeration syntax
  725. @subsection C99-Like Fast Enumeration Syntax
  726. A c99-like declaration syntax is also allowed:
  727. @smallexample
  728. id array = @dots{};
  729. for (id object in array)
  730. @{
  731. /* Do something with 'object' */
  732. @}
  733. @end smallexample
  734. this is completely equivalent to:
  735. @smallexample
  736. id array = @dots{};
  737. @{
  738. id object;
  739. for (object in array)
  740. @{
  741. /* Do something with 'object' */
  742. @}
  743. @}
  744. @end smallexample
  745. but can save some typing.
  746. Note that the option @option{-std=c99} is not required to allow this
  747. syntax in Objective-C.
  748. @c ================================
  749. @node Fast enumeration details
  750. @subsection Fast Enumeration Details
  751. Here is a more technical description with the gory details. Consider the code
  752. @smallexample
  753. for (@var{object expression} in @var{collection expression})
  754. @{
  755. @var{statements}
  756. @}
  757. @end smallexample
  758. here is what happens when you run it:
  759. @itemize @bullet
  760. @item
  761. @code{@var{collection expression}} is evaluated exactly once and the
  762. result is used as the collection object to iterate over. This means
  763. it is safe to write code such as @code{for (object in [NSDictionary
  764. keyEnumerator]) @dots{}}.
  765. @item
  766. the iteration is implemented by the compiler by repeatedly getting
  767. batches of objects from the collection object using the fast
  768. enumeration protocol (see below), then iterating over all objects in
  769. the batch. This is faster than a normal enumeration where objects are
  770. retrieved one by one (hence the name ``fast enumeration'').
  771. @item
  772. if there are no objects in the collection, then
  773. @code{@var{object expression}} is set to @code{nil} and the loop
  774. immediately terminates.
  775. @item
  776. if there are objects in the collection, then for each object in the
  777. collection (in the order they are returned) @code{@var{object expression}}
  778. is set to the object, then @code{@var{statements}} are executed.
  779. @item
  780. @code{@var{statements}} can contain @code{break} and @code{continue}
  781. commands, which will abort the iteration or skip to the next loop
  782. iteration as expected.
  783. @item
  784. when the iteration ends because there are no more objects to iterate
  785. over, @code{@var{object expression}} is set to @code{nil}. This allows
  786. you to determine whether the iteration finished because a @code{break}
  787. command was used (in which case @code{@var{object expression}} will remain
  788. set to the last object that was iterated over) or because it iterated
  789. over all the objects (in which case @code{@var{object expression}} will be
  790. set to @code{nil}).
  791. @item
  792. @code{@var{statements}} must not make any changes to the collection
  793. object; if they do, it is a hard error and the fast enumeration
  794. terminates by invoking @code{objc_enumerationMutation}, a runtime
  795. function that normally aborts the program but which can be customized
  796. by Foundation libraries via @code{objc_set_mutation_handler} to do
  797. something different, such as raising an exception.
  798. @end itemize
  799. @c ================================
  800. @node Fast enumeration protocol
  801. @subsection Fast Enumeration Protocol
  802. If you want your own collection object to be usable with fast
  803. enumeration, you need to have it implement the method
  804. @smallexample
  805. - (unsigned long) countByEnumeratingWithState: (NSFastEnumerationState *)state
  806. objects: (id *)objects
  807. count: (unsigned long)len;
  808. @end smallexample
  809. where @code{NSFastEnumerationState} must be defined in your code as follows:
  810. @smallexample
  811. typedef struct
  812. @{
  813. unsigned long state;
  814. id *itemsPtr;
  815. unsigned long *mutationsPtr;
  816. unsigned long extra[5];
  817. @} NSFastEnumerationState;
  818. @end smallexample
  819. If no @code{NSFastEnumerationState} is defined in your code, the
  820. compiler will automatically replace @code{NSFastEnumerationState *}
  821. with @code{struct __objcFastEnumerationState *}, where that type is
  822. silently defined by the compiler in an identical way. This can be
  823. confusing and we recommend that you define
  824. @code{NSFastEnumerationState} (as shown above) instead.
  825. The method is called repeatedly during a fast enumeration to retrieve
  826. batches of objects. Each invocation of the method should retrieve the
  827. next batch of objects.
  828. The return value of the method is the number of objects in the current
  829. batch; this should not exceed @code{len}, which is the maximum size of
  830. a batch as requested by the caller. The batch itself is returned in
  831. the @code{itemsPtr} field of the @code{NSFastEnumerationState} struct.
  832. To help with returning the objects, the @code{objects} array is a C
  833. array preallocated by the caller (on the stack) of size @code{len}.
  834. In many cases you can put the objects you want to return in that
  835. @code{objects} array, then do @code{itemsPtr = objects}. But you
  836. don't have to; if your collection already has the objects to return in
  837. some form of C array, it could return them from there instead.
  838. The @code{state} and @code{extra} fields of the
  839. @code{NSFastEnumerationState} structure allows your collection object
  840. to keep track of the state of the enumeration. In a simple array
  841. implementation, @code{state} may keep track of the index of the last
  842. object that was returned, and @code{extra} may be unused.
  843. The @code{mutationsPtr} field of the @code{NSFastEnumerationState} is
  844. used to keep track of mutations. It should point to a number; before
  845. working on each object, the fast enumeration loop will check that this
  846. number has not changed. If it has, a mutation has happened and the
  847. fast enumeration will abort. So, @code{mutationsPtr} could be set to
  848. point to some sort of version number of your collection, which is
  849. increased by one every time there is a change (for example when an
  850. object is added or removed). Or, if you are content with less strict
  851. mutation checks, it could point to the number of objects in your
  852. collection or some other value that can be checked to perform an
  853. approximate check that the collection has not been mutated.
  854. Finally, note how we declared the @code{len} argument and the return
  855. value to be of type @code{unsigned long}. They could also be declared
  856. to be of type @code{unsigned int} and everything would still work.
  857. @c =========================================================================
  858. @node Messaging with the GNU Objective-C runtime
  859. @section Messaging with the GNU Objective-C Runtime
  860. This section is specific for the GNU Objective-C runtime. If you are
  861. using a different runtime, you can skip it.
  862. The implementation of messaging in the GNU Objective-C runtime is
  863. designed to be portable, and so is based on standard C.
  864. Sending a message in the GNU Objective-C runtime is composed of two
  865. separate steps. First, there is a call to the lookup function,
  866. @code{objc_msg_lookup ()} (or, in the case of messages to super,
  867. @code{objc_msg_lookup_super ()}). This runtime function takes as
  868. argument the receiver and the selector of the method to be called; it
  869. returns the @code{IMP}, that is a pointer to the function implementing
  870. the method. The second step of method invocation consists of casting
  871. this pointer function to the appropriate function pointer type, and
  872. calling the function pointed to it with the right arguments.
  873. For example, when the compiler encounters a method invocation such as
  874. @code{[object init]}, it compiles it into a call to
  875. @code{objc_msg_lookup (object, @@selector(init))} followed by a cast
  876. of the returned value to the appropriate function pointer type, and
  877. then it calls it.
  878. @menu
  879. * Dynamically registering methods::
  880. * Forwarding hook::
  881. @end menu
  882. @c =========================================================================
  883. @node Dynamically registering methods
  884. @subsection Dynamically Registering Methods
  885. If @code{objc_msg_lookup()} does not find a suitable method
  886. implementation, because the receiver does not implement the required
  887. method, it tries to see if the class can dynamically register the
  888. method.
  889. To do so, the runtime checks if the class of the receiver implements
  890. the method
  891. @smallexample
  892. + (BOOL) resolveInstanceMethod: (SEL)selector;
  893. @end smallexample
  894. in the case of an instance method, or
  895. @smallexample
  896. + (BOOL) resolveClassMethod: (SEL)selector;
  897. @end smallexample
  898. in the case of a class method. If the class implements it, the
  899. runtime invokes it, passing as argument the selector of the original
  900. method, and if it returns @code{YES}, the runtime tries the lookup
  901. again, which could now succeed if a matching method was added
  902. dynamically by @code{+resolveInstanceMethod:} or
  903. @code{+resolveClassMethod:}.
  904. This allows classes to dynamically register methods (by adding them to
  905. the class using @code{class_addMethod}) when they are first called.
  906. To do so, a class should implement @code{+resolveInstanceMethod:} (or,
  907. depending on the case, @code{+resolveClassMethod:}) and have it
  908. recognize the selectors of methods that can be registered dynamically
  909. at runtime, register them, and return @code{YES}. It should return
  910. @code{NO} for methods that it does not dynamically registered at
  911. runtime.
  912. If @code{+resolveInstanceMethod:} (or @code{+resolveClassMethod:}) is
  913. not implemented or returns @code{NO}, the runtime then tries the
  914. forwarding hook.
  915. Support for @code{+resolveInstanceMethod:} and
  916. @code{resolveClassMethod:} was added to the GNU Objective-C runtime in
  917. GCC version 4.6.
  918. @c =========================================================================
  919. @node Forwarding hook
  920. @subsection Forwarding Hook
  921. The GNU Objective-C runtime provides a hook, called
  922. @code{__objc_msg_forward2}, which is called by
  923. @code{objc_msg_lookup()} when it can't find a method implementation in
  924. the runtime tables and after calling @code{+resolveInstanceMethod:}
  925. and @code{+resolveClassMethod:} has been attempted and did not succeed
  926. in dynamically registering the method.
  927. To configure the hook, you set the global variable
  928. @code{__objc_msg_forward2} to a function with the same argument and
  929. return types of @code{objc_msg_lookup()}. When
  930. @code{objc_msg_lookup()} can not find a method implementation, it
  931. invokes the hook function you provided to get a method implementation
  932. to return. So, in practice @code{__objc_msg_forward2} allows you to
  933. extend @code{objc_msg_lookup()} by adding some custom code that is
  934. called to do a further lookup when no standard method implementation
  935. can be found using the normal lookup.
  936. This hook is generally reserved for ``Foundation'' libraries such as
  937. GNUstep Base, which use it to implement their high-level method
  938. forwarding API, typically based around the @code{forwardInvocation:}
  939. method. So, unless you are implementing your own ``Foundation''
  940. library, you should not set this hook.
  941. In a typical forwarding implementation, the @code{__objc_msg_forward2}
  942. hook function determines the argument and return type of the method
  943. that is being looked up, and then creates a function that takes these
  944. arguments and has that return type, and returns it to the caller.
  945. Creating this function is non-trivial and is typically performed using
  946. a dedicated library such as @code{libffi}.
  947. The forwarding method implementation thus created is returned by
  948. @code{objc_msg_lookup()} and is executed as if it was a normal method
  949. implementation. When the forwarding method implementation is called,
  950. it is usually expected to pack all arguments into some sort of object
  951. (typically, an @code{NSInvocation} in a ``Foundation'' library), and
  952. hand it over to the programmer (@code{forwardInvocation:}) who is then
  953. allowed to manipulate the method invocation using a high-level API
  954. provided by the ``Foundation'' library. For example, the programmer
  955. may want to examine the method invocation arguments and name and
  956. potentially change them before forwarding the method invocation to one
  957. or more local objects (@code{performInvocation:}) or even to remote
  958. objects (by using Distributed Objects or some other mechanism). When
  959. all this completes, the return value is passed back and must be
  960. returned correctly to the original caller.
  961. Note that the GNU Objective-C runtime currently provides no support
  962. for method forwarding or method invocations other than the
  963. @code{__objc_msg_forward2} hook.
  964. If the forwarding hook does not exist or returns @code{NULL}, the
  965. runtime currently attempts forwarding using an older, deprecated API,
  966. and if that fails, it aborts the program. In future versions of the
  967. GNU Objective-C runtime, the runtime will immediately abort.