2011-09-21 Tom de Vries <tom@codesourcery.com>
[official-gcc.git] / gcc / doc / objc.texi
blobdd04eda82f78c62a478962f4ba39701e68a3af8f
1 @c Copyright (C) 1988, 1989, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
2 @c 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2010
3 @c Free Software Foundation, Inc.
4 @c This is part of the GCC manual.
5 @c For copying conditions, see the file gcc.texi.
7 @node Objective-C
8 @comment  node-name,  next,  previous,  up
10 @chapter GNU Objective-C features
12 This document is meant to describe some of the GNU Objective-C
13 features.  It is not intended to teach you Objective-C.  There are
14 several resources on the Internet that present the language.
16 @menu
17 * GNU Objective-C runtime API::
18 * Executing code before main::
19 * Type encoding::
20 * Garbage Collection::
21 * Constant string objects::
22 * compatibility_alias::
23 * Exceptions::
24 * Synchronization::
25 * Fast enumeration::
26 * Messaging with the GNU Objective-C runtime::
27 @end menu
29 @c =========================================================================
30 @node GNU Objective-C runtime API
31 @section GNU Objective-C runtime API
33 This section is specific for the GNU Objective-C runtime.  If you are
34 using a different runtime, you can skip it.
36 The GNU Objective-C runtime provides an API that allows you to
37 interact with the Objective-C runtime system, querying the live
38 runtime structures and even manipulating them.  This allows you for
39 example to inspect and navigate classes, methods and protocols; to
40 define new classes or new methods, and even to modify existing classes
41 or protocols.
43 If you are using a ``Foundation'' library such as GNUstep-Base, this
44 library will provide you with a rich set of functionality to do most
45 of the inspection tasks, and you probably will only need direct access
46 to the GNU Objective-C runtime API to define new classes or methods.
48 @menu
49 * Modern GNU Objective-C runtime API::
50 * Traditional GNU Objective-C runtime API::
51 @end menu
53 @c =========================================================================
54 @node Modern GNU Objective-C runtime API
55 @subsection Modern GNU Objective-C runtime API
57 The GNU Objective-C runtime provides an API which is similar to the
58 one provided by the ``Objective-C 2.0'' Apple/NeXT Objective-C
59 runtime.  The API is documented in the public header files of the GNU
60 Objective-C runtime:
62 @itemize @bullet
64 @item
65 @file{objc/objc.h}: this is the basic Objective-C header file,
66 defining the basic Objective-C types such as @code{id}, @code{Class}
67 and @code{BOOL}.  You have to include this header to do almost
68 anything with Objective-C.
70 @item
71 @file{objc/runtime.h}: this header declares most of the public runtime
72 API functions allowing you to inspect and manipulate the Objective-C
73 runtime data structures.  These functions are fairly standardized
74 across Objective-C runtimes and are almost identical to the Apple/NeXT
75 Objective-C runtime ones.  It does not declare functions in some
76 specialized areas (constructing and forwarding message invocations,
77 threading) which are in the other headers below.  You have to include
78 @file{objc/objc.h} and @file{objc/runtime.h} to use any of the
79 functions, such as @code{class_getName()}, declared in
80 @file{objc/runtime.h}.
82 @item
83 @file{objc/message.h}: this header declares public functions used to
84 construct, deconstruct and forward message invocations.  Because
85 messaging is done in quite a different way on different runtimes,
86 functions in this header are specific to the GNU Objective-C runtime
87 implementation.
89 @item
90 @file{objc/objc-exception.h}: this header declares some public
91 functions related to Objective-C exceptions.  For example functions in
92 this header allow you to throw an Objective-C exception from plain
93 C/C++ code.
95 @item
96 @file{objc/objc-sync.h}: this header declares some public functions
97 related to the Objective-C @code{@@synchronized()} syntax, allowing
98 you to emulate an Objective-C @code{@@synchronized()} block in plain
99 C/C++ code.
101 @item
102 @file{objc/thr.h}: this header declares a public runtime API threading
103 layer that is only provided by the GNU Objective-C runtime.  It
104 declares functions such as @code{objc_mutex_lock()}, which provide a
105 platform-independent set of threading functions.
107 @end itemize
109 The header files contain detailed documentation for each function in
110 the GNU Objective-C runtime API.
112 @c =========================================================================
113 @node Traditional GNU Objective-C runtime API
114 @subsection Traditional GNU Objective-C runtime API
116 The GNU Objective-C runtime used to provide a different API, which we
117 call the ``traditional'' GNU Objective-C runtime API.  Functions
118 belonging to this API are easy to recognize because they use a
119 different naming convention, such as @code{class_get_super_class()}
120 (traditional API) instead of @code{class_getSuperclass()} (modern
121 API).  Software using this API includes the file
122 @file{objc/objc-api.h} where it is declared.
124 Starting with GCC 4.7.0, the traditional GNU runtime API is no longer
125 available.
127 @c =========================================================================
128 @node Executing code before main
129 @section @code{+load}: Executing code before main
131 This section is specific for the GNU Objective-C runtime.  If you are
132 using a different runtime, you can skip it.
134 The GNU Objective-C runtime provides a way that allows you to execute
135 code before the execution of the program enters the @code{main}
136 function.  The code is executed on a per-class and a per-category basis,
137 through a special class method @code{+load}.
139 This facility is very useful if you want to initialize global variables
140 which can be accessed by the program directly, without sending a message
141 to the class first.  The usual way to initialize global variables, in the
142 @code{+initialize} method, might not be useful because
143 @code{+initialize} is only called when the first message is sent to a
144 class object, which in some cases could be too late.
146 Suppose for example you have a @code{FileStream} class that declares
147 @code{Stdin}, @code{Stdout} and @code{Stderr} as global variables, like
148 below:
150 @smallexample
152 FileStream *Stdin = nil;
153 FileStream *Stdout = nil;
154 FileStream *Stderr = nil;
156 @@implementation FileStream
158 + (void)initialize
160     Stdin = [[FileStream new] initWithFd:0];
161     Stdout = [[FileStream new] initWithFd:1];
162     Stderr = [[FileStream new] initWithFd:2];
165 /* @r{Other methods here} */
166 @@end
168 @end smallexample
170 In this example, the initialization of @code{Stdin}, @code{Stdout} and
171 @code{Stderr} in @code{+initialize} occurs too late.  The programmer can
172 send a message to one of these objects before the variables are actually
173 initialized, thus sending messages to the @code{nil} object.  The
174 @code{+initialize} method which actually initializes the global
175 variables is not invoked until the first message is sent to the class
176 object.  The solution would require these variables to be initialized
177 just before entering @code{main}.
179 The correct solution of the above problem is to use the @code{+load}
180 method instead of @code{+initialize}:
182 @smallexample
184 @@implementation FileStream
186 + (void)load
188     Stdin = [[FileStream new] initWithFd:0];
189     Stdout = [[FileStream new] initWithFd:1];
190     Stderr = [[FileStream new] initWithFd:2];
193 /* @r{Other methods here} */
194 @@end
196 @end smallexample
198 The @code{+load} is a method that is not overridden by categories.  If a
199 class and a category of it both implement @code{+load}, both methods are
200 invoked.  This allows some additional initializations to be performed in
201 a category.
203 This mechanism is not intended to be a replacement for @code{+initialize}.
204 You should be aware of its limitations when you decide to use it
205 instead of @code{+initialize}.
207 @menu
208 * What you can and what you cannot do in +load::
209 @end menu
212 @node What you can and what you cannot do in +load
213 @subsection What you can and what you cannot do in @code{+load}
215 @code{+load} is to be used only as a last resort.  Because it is
216 executed very early, most of the Objective-C runtime machinery will
217 not be ready when @code{+load} is executed; hence @code{+load} works
218 best for executing C code that is independent on the Objective-C
219 runtime.
221 The @code{+load} implementation in the GNU runtime guarantees you the
222 following things:
224 @itemize @bullet
226 @item
227 you can write whatever C code you like;
229 @item
230 you can allocate and send messages to objects whose class is implemented
231 in the same file;
233 @item
234 the @code{+load} implementation of all super classes of a class are
235 executed before the @code{+load} of that class is executed;
237 @item
238 the @code{+load} implementation of a class is executed before the
239 @code{+load} implementation of any category.
241 @end itemize
243 In particular, the following things, even if they can work in a
244 particular case, are not guaranteed:
246 @itemize @bullet
248 @item
249 allocation of or sending messages to arbitrary objects;
251 @item
252 allocation of or sending messages to objects whose classes have a
253 category implemented in the same file;
255 @item
256 sending messages to Objective-C constant strings (@code{@@"this is a
257 constant string"});
259 @end itemize
261 You should make no assumptions about receiving @code{+load} in sibling
262 classes when you write @code{+load} of a class.  The order in which
263 sibling classes receive @code{+load} is not guaranteed.
265 The order in which @code{+load} and @code{+initialize} are called could
266 be problematic if this matters.  If you don't allocate objects inside
267 @code{+load}, it is guaranteed that @code{+load} is called before
268 @code{+initialize}.  If you create an object inside @code{+load} the
269 @code{+initialize} method of object's class is invoked even if
270 @code{+load} was not invoked.  Note if you explicitly call @code{+load}
271 on a class, @code{+initialize} will be called first.  To avoid possible
272 problems try to implement only one of these methods.
274 The @code{+load} method is also invoked when a bundle is dynamically
275 loaded into your running program.  This happens automatically without any
276 intervening operation from you.  When you write bundles and you need to
277 write @code{+load} you can safely create and send messages to objects whose
278 classes already exist in the running program.  The same restrictions as
279 above apply to classes defined in bundle.
283 @node Type encoding
284 @section Type encoding
286 This is an advanced section.  Type encodings are used extensively by
287 the compiler and by the runtime, but you generally do not need to know
288 about them to use Objective-C.
290 The Objective-C compiler generates type encodings for all the types.
291 These type encodings are used at runtime to find out information about
292 selectors and methods and about objects and classes.
294 The types are encoded in the following way:
296 @c @sp 1
298 @multitable @columnfractions .25 .75
299 @item @code{_Bool}
300 @tab @code{B}
301 @item @code{char}
302 @tab @code{c}
303 @item @code{unsigned char}
304 @tab @code{C}
305 @item @code{short}
306 @tab @code{s}
307 @item @code{unsigned short}
308 @tab @code{S}
309 @item @code{int}
310 @tab @code{i}
311 @item @code{unsigned int}
312 @tab @code{I}
313 @item @code{long}
314 @tab @code{l}
315 @item @code{unsigned long}
316 @tab @code{L}
317 @item @code{long long}
318 @tab @code{q}
319 @item @code{unsigned long long}
320 @tab @code{Q}
321 @item @code{float}
322 @tab @code{f}
323 @item @code{double}
324 @tab @code{d}
325 @item @code{long double}
326 @tab @code{D}
327 @item @code{void}
328 @tab @code{v}
329 @item @code{id}
330 @tab @code{@@}
331 @item @code{Class}
332 @tab @code{#}
333 @item @code{SEL}
334 @tab @code{:}
335 @item @code{char*}
336 @tab @code{*}
337 @item @code{enum}
338 @tab an @code{enum} is encoded exactly as the integer type that the compiler uses for it, which depends on the enumeration
339 values.  Often the compiler users @code{unsigned int}, which is then encoded as @code{I}.
340 @item unknown type
341 @tab @code{?}
342 @item Complex types
343 @tab @code{j} followed by the inner type.  For example @code{_Complex double} is encoded as "jd".
344 @item bit-fields
345 @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)
346 @end multitable
348 @c @sp 1
350 The encoding of bit-fields has changed to allow bit-fields to be
351 properly handled by the runtime functions that compute sizes and
352 alignments of types that contain bit-fields.  The previous encoding
353 contained only the size of the bit-field.  Using only this information
354 it is not possible to reliably compute the size occupied by the
355 bit-field.  This is very important in the presence of the Boehm's
356 garbage collector because the objects are allocated using the typed
357 memory facility available in this collector.  The typed memory
358 allocation requires information about where the pointers are located
359 inside the object.
361 The position in the bit-field is the position, counting in bits, of the
362 bit closest to the beginning of the structure.
364 The non-atomic types are encoded as follows:
366 @c @sp 1
368 @multitable @columnfractions .2 .8
369 @item pointers
370 @tab @samp{^} followed by the pointed type.
371 @item arrays
372 @tab @samp{[} followed by the number of elements in the array followed by the type of the elements followed by @samp{]}
373 @item structures
374 @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{@}}
375 @item unions
376 @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{)}
377 @item vectors
378 @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{]}
379 @end multitable
381 Here are some types and their encodings, as they are generated by the
382 compiler on an i386 machine:
384 @sp 1
386 @multitable @columnfractions .25 .75
387 @item Objective-C type
388 @tab Compiler encoding
389 @item
390 @smallexample
391 int a[10];
392 @end smallexample
393 @tab @code{[10i]}
394 @item
395 @smallexample
396 struct @{
397   int i;
398   float f[3];
399   int a:3;
400   int b:2;
401   char c;
403 @end smallexample
404 @tab @code{@{?=i[3f]b128i3b131i2c@}}
405 @item
406 @smallexample
407 int a __attribute__ ((vector_size (16)));
408 @end smallexample
409 @tab @code{![16,16i]} (alignment would depend on the machine)
410 @end multitable
412 @sp 1
414 In addition to the types the compiler also encodes the type
415 specifiers.  The table below describes the encoding of the current
416 Objective-C type specifiers:
418 @sp 1
420 @multitable @columnfractions .25 .75
421 @item Specifier
422 @tab Encoding
423 @item @code{const}
424 @tab @code{r}
425 @item @code{in}
426 @tab @code{n}
427 @item @code{inout}
428 @tab @code{N}
429 @item @code{out}
430 @tab @code{o}
431 @item @code{bycopy}
432 @tab @code{O}
433 @item @code{byref}
434 @tab @code{R}
435 @item @code{oneway}
436 @tab @code{V}
437 @end multitable
439 @sp 1
441 The type specifiers are encoded just before the type.  Unlike types
442 however, the type specifiers are only encoded when they appear in method
443 argument types.
445 Note how @code{const} interacts with pointers:
447 @sp 1
449 @multitable @columnfractions .25 .75
450 @item Objective-C type
451 @tab Compiler encoding
452 @item
453 @smallexample
454 const int
455 @end smallexample
456 @tab @code{ri}
457 @item
458 @smallexample
459 const int*
460 @end smallexample
461 @tab @code{^ri}
462 @item
463 @smallexample
464 int *const
465 @end smallexample
466 @tab @code{r^i}
467 @end multitable
469 @sp 1
471 @code{const int*} is a pointer to a @code{const int}, and so is
472 encoded as @code{^ri}.  @code{int* const}, instead, is a @code{const}
473 pointer to an @code{int}, and so is encoded as @code{r^i}.
475 Finally, there is a complication when encoding @code{const char *}
476 versus @code{char * const}.  Because @code{char *} is encoded as
477 @code{*} and not as @code{^c}, there is no way to express the fact
478 that @code{r} applies to the pointer or to the pointee.
480 Hence, it is assumed as a convention that @code{r*} means @code{const
481 char *} (since it is what is most often meant), and there is no way to
482 encode @code{char *const}.  @code{char *const} would simply be encoded
483 as @code{*}, and the @code{const} is lost.
485 @menu
486 * Legacy type encoding::
487 * @@encode::
488 * Method signatures::
489 @end menu
491 @node Legacy type encoding
492 @subsection Legacy type encoding
494 Unfortunately, historically GCC used to have a number of bugs in its
495 encoding code.  The NeXT runtime expects GCC to emit type encodings in
496 this historical format (compatible with GCC-3.3), so when using the
497 NeXT runtime, GCC will introduce on purpose a number of incorrect
498 encodings:
500 @itemize @bullet
502 @item
503 the read-only qualifier of the pointee gets emitted before the '^'.
504 The read-only qualifier of the pointer itself gets ignored, unless it
505 is a typedef.  Also, the 'r' is only emitted for the outermost type.
507 @item
508 32-bit longs are encoded as 'l' or 'L', but not always.  For typedefs,
509 the compiler uses 'i' or 'I' instead if encoding a struct field or a
510 pointer.
512 @item
513 @code{enum}s are always encoded as 'i' (int) even if they are actually
514 unsigned or long.
516 @end itemize
518 In addition to that, the NeXT runtime uses a different encoding for
519 bitfields.  It encodes them as @code{b} followed by the size, without
520 a bit offset or the underlying field type.
522 @node @@encode
523 @subsection @@encode
525 GNU Objective-C supports the @code{@@encode} syntax that allows you to
526 create a type encoding from a C/Objective-C type.  For example,
527 @code{@@encode(int)} is compiled by the compiler into @code{"i"}.
529 @code{@@encode} does not support type qualifiers other than
530 @code{const}.  For example, @code{@@encode(const char*)} is valid and
531 is compiled into @code{"r*"}, while @code{@@encode(bycopy char *)} is
532 invalid and will cause a compilation error.
534 @node Method signatures
535 @subsection Method signatures
537 This section documents the encoding of method types, which is rarely
538 needed to use Objective-C.  You should skip it at a first reading; the
539 runtime provides functions that will work on methods and can walk
540 through the list of parameters and interpret them for you.  These
541 functions are part of the public ``API'' and are the preferred way to
542 interact with method signatures from user code.
544 But if you need to debug a problem with method signatures and need to
545 know how they are implemented (i.e., the ``ABI''), read on.
547 Methods have their ``signature'' encoded and made available to the
548 runtime.  The ``signature'' encodes all the information required to
549 dynamically build invocations of the method at runtime: return type
550 and arguments.
552 The ``signature'' is a null-terminated string, composed of the following:
554 @itemize @bullet
556 @item
557 The return type, including type qualifiers.  For example, a method
558 returning @code{int} would have @code{i} here.
560 @item
561 The total size (in bytes) required to pass all the parameters.  This
562 includes the two hidden parameters (the object @code{self} and the
563 method selector @code{_cmd}).
565 @item
566 Each argument, with the type encoding, followed by the offset (in
567 bytes) of the argument in the list of parameters.
569 @end itemize
571 For example, a method with no arguments and returning @code{int} would
572 have the signature @code{i8@@0:4} if the size of a pointer is 4.  The
573 signature is interpreted as follows: the @code{i} is the return type
574 (an @code{int}), the @code{8} is the total size of the parameters in
575 bytes (two pointers each of size 4), the @code{@@0} is the first
576 parameter (an object at byte offset @code{0}) and @code{:4} is the
577 second parameter (a @code{SEL} at byte offset @code{4}).
579 You can easily find more examples by running the ``strings'' program
580 on an Objective-C object file compiled by GCC.  You'll see a lot of
581 strings that look very much like @code{i8@@0:4}.  They are signatures
582 of Objective-C methods.
585 @node Garbage Collection
586 @section Garbage Collection
588 This section is specific for the GNU Objective-C runtime.  If you are
589 using a different runtime, you can skip it.
591 Support for garbage collection with the GNU runtime has been added by
592 using a powerful conservative garbage collector, known as the
593 Boehm-Demers-Weiser conservative garbage collector.
595 To enable the support for it you have to configure the compiler using
596 an additional argument, @w{@option{--enable-objc-gc}}.  This will
597 build the boehm-gc library, and build an additional runtime library
598 which has several enhancements to support the garbage collector.  The
599 new library has a new name, @file{libobjc_gc.a} to not conflict with
600 the non-garbage-collected library.
602 When the garbage collector is used, the objects are allocated using the
603 so-called typed memory allocation mechanism available in the
604 Boehm-Demers-Weiser collector.  This mode requires precise information on
605 where pointers are located inside objects.  This information is computed
606 once per class, immediately after the class has been initialized.
608 There is a new runtime function @code{class_ivar_set_gcinvisible()}
609 which can be used to declare a so-called @dfn{weak pointer}
610 reference.  Such a pointer is basically hidden for the garbage collector;
611 this can be useful in certain situations, especially when you want to
612 keep track of the allocated objects, yet allow them to be
613 collected.  This kind of pointers can only be members of objects, you
614 cannot declare a global pointer as a weak reference.  Every type which is
615 a pointer type can be declared a weak pointer, including @code{id},
616 @code{Class} and @code{SEL}.
618 Here is an example of how to use this feature.  Suppose you want to
619 implement a class whose instances hold a weak pointer reference; the
620 following class does this:
622 @smallexample
624 @@interface WeakPointer : Object
626     const void* weakPointer;
629 - initWithPointer:(const void*)p;
630 - (const void*)weakPointer;
631 @@end
634 @@implementation WeakPointer
636 + (void)initialize
638   class_ivar_set_gcinvisible (self, "weakPointer", YES);
641 - initWithPointer:(const void*)p
643   weakPointer = p;
644   return self;
647 - (const void*)weakPointer
649   return weakPointer;
652 @@end
654 @end smallexample
656 Weak pointers are supported through a new type character specifier
657 represented by the @samp{!} character.  The
658 @code{class_ivar_set_gcinvisible()} function adds or removes this
659 specifier to the string type description of the instance variable named
660 as argument.
662 @c =========================================================================
663 @node Constant string objects
664 @section Constant string objects
666 GNU Objective-C provides constant string objects that are generated
667 directly by the compiler.  You declare a constant string object by
668 prefixing a C constant string with the character @samp{@@}:
670 @smallexample
671   id myString = @@"this is a constant string object";
672 @end smallexample
674 The constant string objects are by default instances of the
675 @code{NXConstantString} class which is provided by the GNU Objective-C
676 runtime.  To get the definition of this class you must include the
677 @file{objc/NXConstStr.h} header file.
679 User defined libraries may want to implement their own constant string
680 class.  To be able to support them, the GNU Objective-C compiler provides
681 a new command line options @option{-fconstant-string-class=@var{class-name}}.
682 The provided class should adhere to a strict structure, the same
683 as @code{NXConstantString}'s structure:
685 @smallexample
687 @@interface MyConstantStringClass
689   Class isa;
690   char *c_string;
691   unsigned int len;
693 @@end
695 @end smallexample
697 @code{NXConstantString} inherits from @code{Object}; user class
698 libraries may choose to inherit the customized constant string class
699 from a different class than @code{Object}.  There is no requirement in
700 the methods the constant string class has to implement, but the final
701 ivar layout of the class must be the compatible with the given
702 structure.
704 When the compiler creates the statically allocated constant string
705 object, the @code{c_string} field will be filled by the compiler with
706 the string; the @code{length} field will be filled by the compiler with
707 the string length; the @code{isa} pointer will be filled with
708 @code{NULL} by the compiler, and it will later be fixed up automatically
709 at runtime by the GNU Objective-C runtime library to point to the class
710 which was set by the @option{-fconstant-string-class} option when the
711 object file is loaded (if you wonder how it works behind the scenes, the
712 name of the class to use, and the list of static objects to fixup, are
713 stored by the compiler in the object file in a place where the GNU
714 runtime library will find them at runtime).
716 As a result, when a file is compiled with the
717 @option{-fconstant-string-class} option, all the constant string objects
718 will be instances of the class specified as argument to this option.  It
719 is possible to have multiple compilation units referring to different
720 constant string classes, neither the compiler nor the linker impose any
721 restrictions in doing this.
723 @c =========================================================================
724 @node compatibility_alias
725 @section compatibility_alias
727 The keyword @code{@@compatibility_alias} allows you to define a class name
728 as equivalent to another class name.  For example:
730 @smallexample
731 @@compatibility_alias WOApplication GSWApplication;
732 @end smallexample
734 tells the compiler that each time it encounters @code{WOApplication} as
735 a class name, it should replace it with @code{GSWApplication} (that is,
736 @code{WOApplication} is just an alias for @code{GSWApplication}).
738 There are some constraints on how this can be used---
740 @itemize @bullet
742 @item @code{WOApplication} (the alias) must not be an existing class;
744 @item @code{GSWApplication} (the real class) must be an existing class.
746 @end itemize
748 @c =========================================================================
749 @node Exceptions
750 @section Exceptions
752 GNU Objective-C provides exception support built into the language, as
753 in the following example:
755 @smallexample
756   @@try @{
757     @dots{}
758        @@throw expr;
759     @dots{}
760   @}
761   @@catch (AnObjCClass *exc) @{
762     @dots{}
763       @@throw expr;
764     @dots{}
765       @@throw;
766     @dots{}
767   @}
768   @@catch (AnotherClass *exc) @{
769     @dots{}
770   @}
771   @@catch (id allOthers) @{
772     @dots{}
773   @}
774   @@finally @{
775     @dots{}
776       @@throw expr;
777     @dots{}
778   @}
779 @end smallexample
781 The @code{@@throw} statement may appear anywhere in an Objective-C or
782 Objective-C++ program; when used inside of a @code{@@catch} block, the
783 @code{@@throw} may appear without an argument (as shown above), in
784 which case the object caught by the @code{@@catch} will be rethrown.
786 Note that only (pointers to) Objective-C objects may be thrown and
787 caught using this scheme.  When an object is thrown, it will be caught
788 by the nearest @code{@@catch} clause capable of handling objects of
789 that type, analogously to how @code{catch} blocks work in C++ and
790 Java.  A @code{@@catch(id @dots{})} clause (as shown above) may also
791 be provided to catch any and all Objective-C exceptions not caught by
792 previous @code{@@catch} clauses (if any).
794 The @code{@@finally} clause, if present, will be executed upon exit
795 from the immediately preceding @code{@@try @dots{} @@catch} section.
796 This will happen regardless of whether any exceptions are thrown,
797 caught or rethrown inside the @code{@@try @dots{} @@catch} section,
798 analogously to the behavior of the @code{finally} clause in Java.
800 There are several caveats to using the new exception mechanism:
802 @itemize @bullet
803 @item
804 The @option{-fobjc-exceptions} command line option must be used when
805 compiling Objective-C files that use exceptions.
807 @item
808 With the GNU runtime, exceptions are always implemented as ``native''
809 exceptions and it is recommended that the @option{-fexceptions} and
810 @option{-shared-libgcc} options are used when linking.
812 @item
813 With the NeXT runtime, although currently designed to be binary
814 compatible with @code{NS_HANDLER}-style idioms provided by the
815 @code{NSException} class, the new exceptions can only be used on Mac
816 OS X 10.3 (Panther) and later systems, due to additional functionality
817 needed in the NeXT Objective-C runtime.
819 @item
820 As mentioned above, the new exceptions do not support handling
821 types other than Objective-C objects.   Furthermore, when used from
822 Objective-C++, the Objective-C exception model does not interoperate with C++
823 exceptions at this time.  This means you cannot @code{@@throw} an exception
824 from Objective-C and @code{catch} it in C++, or vice versa
825 (i.e., @code{throw @dots{} @@catch}).
826 @end itemize
828 @c =========================================================================
829 @node Synchronization
830 @section Synchronization
832 GNU Objective-C provides support for synchronized blocks:
834 @smallexample
835   @@synchronized (ObjCClass *guard) @{
836     @dots{}
837   @}
838 @end smallexample
840 Upon entering the @code{@@synchronized} block, a thread of execution
841 shall first check whether a lock has been placed on the corresponding
842 @code{guard} object by another thread.  If it has, the current thread
843 shall wait until the other thread relinquishes its lock.  Once
844 @code{guard} becomes available, the current thread will place its own
845 lock on it, execute the code contained in the @code{@@synchronized}
846 block, and finally relinquish the lock (thereby making @code{guard}
847 available to other threads).
849 Unlike Java, Objective-C does not allow for entire methods to be
850 marked @code{@@synchronized}.  Note that throwing exceptions out of
851 @code{@@synchronized} blocks is allowed, and will cause the guarding
852 object to be unlocked properly.
854 Because of the interactions between synchronization and exception
855 handling, you can only use @code{@@synchronized} when compiling with
856 exceptions enabled, that is with the command line option
857 @option{-fobjc-exceptions}.
860 @c =========================================================================
861 @node Fast enumeration
862 @section Fast enumeration
864 @menu
865 * Using fast enumeration::
866 * c99-like fast enumeration syntax::
867 * Fast enumeration details::
868 * Fast enumeration protocol::
869 @end menu
871 @c ================================
872 @node Using fast enumeration
873 @subsection Using fast enumeration
875 GNU Objective-C provides support for the fast enumeration syntax:
877 @smallexample
878   id array = @dots{};
879   id object;
881   for (object in array)
882   @{
883     /* Do something with 'object' */
884   @}
885 @end smallexample
887 @code{array} needs to be an Objective-C object (usually a collection
888 object, for example an array, a dictionary or a set) which implements
889 the ``Fast Enumeration Protocol'' (see below).  If you are using a
890 Foundation library such as GNUstep Base or Apple Cocoa Foundation, all
891 collection objects in the library implement this protocol and can be
892 used in this way.
894 The code above would iterate over all objects in @code{array}.  For
895 each of them, it assigns it to @code{object}, then executes the
896 @code{Do something with 'object'} statements.
898 Here is a fully worked-out example using a Foundation library (which
899 provides the implementation of @code{NSArray}, @code{NSString} and
900 @code{NSLog}):
902 @smallexample
903   NSArray *array = [NSArray arrayWithObjects: @@"1", @@"2", @@"3", nil];
904   NSString *object;
906   for (object in array)
907     NSLog (@@"Iterating over %@@", object);
908 @end smallexample
911 @c ================================
912 @node c99-like fast enumeration syntax
913 @subsection c99-like fast enumeration syntax
915 A c99-like declaration syntax is also allowed:
917 @smallexample
918   id array = @dots{};
920   for (id object in array)
921   @{
922     /* Do something with 'object'  */
923   @}
924 @end smallexample
926 this is completely equivalent to:
928 @smallexample
929   id array = @dots{};
931   @{
932     id object;
933     for (object in array)
934     @{
935       /* Do something with 'object'  */
936     @}
937   @}
938 @end smallexample
940 but can save some typing.
942 Note that the option @option{-std=c99} is not required to allow this
943 syntax in Objective-C.
945 @c ================================
946 @node Fast enumeration details
947 @subsection Fast enumeration details
949 Here is a more technical description with the gory details.  Consider the code
951 @smallexample
952   for (@var{object expression} in @var{collection expression})
953   @{
954     @var{statements}
955   @}
956 @end smallexample
958 here is what happens when you run it:
960 @itemize @bullet
961 @item
962 @code{@var{collection expression}} is evaluated exactly once and the
963 result is used as the collection object to iterate over.  This means
964 it is safe to write code such as @code{for (object in [NSDictionary
965 keyEnumerator]) @dots{}}.
967 @item
968 the iteration is implemented by the compiler by repeatedly getting
969 batches of objects from the collection object using the fast
970 enumeration protocol (see below), then iterating over all objects in
971 the batch.  This is faster than a normal enumeration where objects are
972 retrieved one by one (hence the name ``fast enumeration'').
974 @item
975 if there are no objects in the collection, then
976 @code{@var{object expression}} is set to @code{nil} and the loop
977 immediately terminates.
979 @item
980 if there are objects in the collection, then for each object in the
981 collection (in the order they are returned) @code{@var{object expression}}
982 is set to the object, then @code{@var{statements}} are executed.
984 @item
985 @code{@var{statements}} can contain @code{break} and @code{continue}
986 commands, which will abort the iteration or skip to the next loop
987 iteration as expected.
989 @item
990 when the iteration ends because there are no more objects to iterate
991 over, @code{@var{object expression}} is set to @code{nil}.  This allows
992 you to determine whether the iteration finished because a @code{break}
993 command was used (in which case @code{@var{object expression}} will remain
994 set to the last object that was iterated over) or because it iterated
995 over all the objects (in which case @code{@var{object expression}} will be
996 set to @code{nil}).
998 @item
999 @code{@var{statements}} must not make any changes to the collection
1000 object; if they do, it is a hard error and the fast enumeration
1001 terminates by invoking @code{objc_enumerationMutation}, a runtime
1002 function that normally aborts the program but which can be customized
1003 by Foundation libraries via @code{objc_set_mutation_handler} to do
1004 something different, such as raising an exception.
1006 @end itemize
1008 @c ================================
1009 @node Fast enumeration protocol
1010 @subsection Fast enumeration protocol
1012 If you want your own collection object to be usable with fast
1013 enumeration, you need to have it implement the method
1015 @smallexample
1016 - (unsigned long) countByEnumeratingWithState: (NSFastEnumerationState *)state
1017                                       objects: (id *)objects
1018                                         count: (unsigned long)len;
1019 @end smallexample
1021 where @code{NSFastEnumerationState} must be defined in your code as follows:
1023 @smallexample
1024 typedef struct
1026   unsigned long state;
1027   id            *itemsPtr;
1028   unsigned long *mutationsPtr;
1029   unsigned long extra[5];
1030 @} NSFastEnumerationState;
1031 @end smallexample
1033 If no @code{NSFastEnumerationState} is defined in your code, the
1034 compiler will automatically replace @code{NSFastEnumerationState *}
1035 with @code{struct __objcFastEnumerationState *}, where that type is
1036 silently defined by the compiler in an identical way.  This can be
1037 confusing and we recommend that you define
1038 @code{NSFastEnumerationState} (as shown above) instead.
1040 The method is called repeatedly during a fast enumeration to retrieve
1041 batches of objects.  Each invocation of the method should retrieve the
1042 next batch of objects.
1044 The return value of the method is the number of objects in the current
1045 batch; this should not exceed @code{len}, which is the maximum size of
1046 a batch as requested by the caller.  The batch itself is returned in
1047 the @code{itemsPtr} field of the @code{NSFastEnumerationState} struct.
1049 To help with returning the objects, the @code{objects} array is a C
1050 array preallocated by the caller (on the stack) of size @code{len}.
1051 In many cases you can put the objects you want to return in that
1052 @code{objects} array, then do @code{itemsPtr = objects}.  But you
1053 don't have to; if your collection already has the objects to return in
1054 some form of C array, it could return them from there instead.
1056 The @code{state} and @code{extra} fields of the
1057 @code{NSFastEnumerationState} structure allows your collection object
1058 to keep track of the state of the enumeration.  In a simple array
1059 implementation, @code{state} may keep track of the index of the last
1060 object that was returned, and @code{extra} may be unused.
1062 The @code{mutationsPtr} field of the @code{NSFastEnumerationState} is
1063 used to keep track of mutations.  It should point to a number; before
1064 working on each object, the fast enumeration loop will check that this
1065 number has not changed.  If it has, a mutation has happened and the
1066 fast enumeration will abort.  So, @code{mutationsPtr} could be set to
1067 point to some sort of version number of your collection, which is
1068 increased by one every time there is a change (for example when an
1069 object is added or removed).  Or, if you are content with less strict
1070 mutation checks, it could point to the number of objects in your
1071 collection or some other value that can be checked to perform an
1072 approximate check that the collection has not been mutated.
1074 Finally, note how we declared the @code{len} argument and the return
1075 value to be of type @code{unsigned long}.  They could also be declared
1076 to be of type @code{unsigned int} and everything would still work.
1078 @c =========================================================================
1079 @node Messaging with the GNU Objective-C runtime
1080 @section Messaging with the GNU Objective-C runtime
1082 This section is specific for the GNU Objective-C runtime.  If you are
1083 using a different runtime, you can skip it.
1085 The implementation of messaging in the GNU Objective-C runtime is
1086 designed to be portable, and so is based on standard C.
1088 Sending a message in the GNU Objective-C runtime is composed of two
1089 separate steps.  First, there is a call to the lookup function,
1090 @code{objc_msg_lookup ()} (or, in the case of messages to super,
1091 @code{objc_msg_lookup_super ()}).  This runtime function takes as
1092 argument the receiver and the selector of the method to be called; it
1093 returns the @code{IMP}, that is a pointer to the function implementing
1094 the method.  The second step of method invocation consists of casting
1095 this pointer function to the appropriate function pointer type, and
1096 calling the function pointed to it with the right arguments.
1098 For example, when the compiler encounters a method invocation such as
1099 @code{[object init]}, it compiles it into a call to
1100 @code{objc_msg_lookup (object, @@selector(init))} followed by a cast
1101 of the returned value to the appropriate function pointer type, and
1102 then it calls it.
1104 @menu
1105 * Dynamically registering methods::
1106 * Forwarding hook::
1107 @end menu
1109 @c =========================================================================
1110 @node Dynamically registering methods
1111 @subsection Dynamically registering methods
1113 If @code{objc_msg_lookup()} does not find a suitable method
1114 implementation, because the receiver does not implement the required
1115 method, it tries to see if the class can dynamically register the
1116 method.
1118 To do so, the runtime checks if the class of the receiver implements
1119 the method
1121 @smallexample
1122 + (BOOL) resolveInstanceMethod: (SEL)selector;
1123 @end smallexample
1125 in the case of an instance method, or
1127 @smallexample
1128 + (BOOL) resolveClassMethod: (SEL)selector;
1129 @end smallexample
1131 in the case of a class method.  If the class implements it, the
1132 runtime invokes it, passing as argument the selector of the original
1133 method, and if it returns @code{YES}, the runtime tries the lookup
1134 again, which could now succeed if a matching method was added
1135 dynamically by @code{+resolveInstanceMethod:} or
1136 @code{+resolveClassMethod:}.
1138 This allows classes to dynamically register methods (by adding them to
1139 the class using @code{class_addMethod}) when they are first called.
1140 To do so, a class should implement @code{+resolveInstanceMethod:} (or,
1141 depending on the case, @code{+resolveClassMethod:}) and have it
1142 recognize the selectors of methods that can be registered dynamically
1143 at runtime, register them, and return @code{YES}.  It should return
1144 @code{NO} for methods that it does not dynamically registered at
1145 runtime.
1147 If @code{+resolveInstanceMethod:} (or @code{+resolveClassMethod:}) is
1148 not implemented or returns @code{NO}, the runtime then tries the
1149 forwarding hook.
1151 Support for @code{+resolveInstanceMethod:} and
1152 @code{resolveClassMethod:} was added to the GNU Objective-C runtime in
1153 GCC version 4.6.
1155 @c =========================================================================
1156 @node Forwarding hook
1157 @subsection Forwarding hook
1159 The GNU Objective-C runtime provides a hook, called
1160 @code{__objc_msg_forward2}, which is called by
1161 @code{objc_msg_lookup()} when it can't find a method implementation in
1162 the runtime tables and after calling @code{+resolveInstanceMethod:}
1163 and @code{+resolveClassMethod:} has been attempted and did not succeed
1164 in dynamically registering the method.
1166 To configure the hook, you set the global variable
1167 @code{__objc_msg_foward2} to a function with the same argument and
1168 return types of @code{objc_msg_lookup()}.  When
1169 @code{objc_msg_lookup()} can not find a method implementation, it
1170 invokes the hook function you provided to get a method implementation
1171 to return.  So, in practice @code{__objc_msg_forward2} allows you to
1172 extend @code{objc_msg_lookup()} by adding some custom code that is
1173 called to do a further lookup when no standard method implementation
1174 can be found using the normal lookup.
1176 This hook is generally reserved for ``Foundation'' libraries such as
1177 GNUstep Base, which use it to implement their high-level method
1178 forwarding API, typically based around the @code{forwardInvocation:}
1179 method.  So, unless you are implementing your own ``Foundation''
1180 library, you should not set this hook.
1182 In a typical forwarding implementation, the @code{__objc_msg_forward2}
1183 hook function determines the argument and return type of the method
1184 that is being looked up, and then creates a function that takes these
1185 arguments and has that return type, and returns it to the caller.
1186 Creating this function is non-trivial and is typically performed using
1187 a dedicated library such as @code{libffi}.
1189 The forwarding method implementation thus created is returned by
1190 @code{objc_msg_lookup()} and is executed as if it was a normal method
1191 implementation.  When the forwarding method implementation is called,
1192 it is usually expected to pack all arguments into some sort of object
1193 (typically, an @code{NSInvocation} in a ``Foundation'' library), and
1194 hand it over to the programmer (@code{forwardInvocation:}) who is then
1195 allowed to manipulate the method invocation using a high-level API
1196 provided by the ``Foundation'' library.  For example, the programmer
1197 may want to examine the method invocation arguments and name and
1198 potentially change them before forwarding the method invocation to one
1199 or more local objects (@code{performInvocation:}) or even to remote
1200 objects (by using Distributed Objects or some other mechanism).  When
1201 all this completes, the return value is passed back and must be
1202 returned correctly to the original caller.
1204 Note that the GNU Objective-C runtime currently provides no support
1205 for method forwarding or method invocations other than the
1206 @code{__objc_msg_forward2} hook.
1208 If the forwarding hook does not exist or returns @code{NULL}, the
1209 runtime currently attempts forwarding using an older, deprecated API,
1210 and if that fails, it aborts the program.  In future versions of the
1211 GNU Objective-C runtime, the runtime will immediately abort.