OSDN Git Service

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