OSDN Git Service

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