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.
7 @comment node-name, next, previous, up
9 @chapter GNU Objective-C features
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.
16 * GNU Objective-C runtime API::
17 * Executing code before main::
19 * Garbage Collection::
20 * Constant string objects::
21 * compatibility_alias::
25 * Messaging with the GNU Objective-C runtime::
28 @c =========================================================================
29 @node GNU Objective-C runtime API
30 @section GNU Objective-C runtime API
32 This section is specific for the GNU Objective-C runtime. If you are
33 using a different runtime, you can skip it.
35 The GNU Objective-C runtime provides an API that allows you to
36 interact with the Objective-C runtime system, querying the live
37 runtime structures and even manipulating them. This allows you for
38 example to inspect and navigate classes, methods and protocols; to
39 define new classes or new methods, and even to modify existing classes
42 If you are using a ``Foundation'' library such as GNUstep-Base, this
43 library will provide you with a rich set of functionality to do most
44 of the inspection tasks, and you probably will only need direct access
45 to the GNU Objective-C runtime API to define new classes or methods.
48 * Modern GNU Objective-C runtime API::
49 * Traditional GNU Objective-C runtime API::
52 @c =========================================================================
53 @node Modern GNU Objective-C runtime API
54 @subsection Modern GNU Objective-C runtime API
56 The GNU Objective-C runtime provides an API which is similar to the
57 one provided by the ``Objective-C 2.0'' Apple/NeXT Objective-C
58 runtime. The API is documented in the public header files of the GNU
64 @file{objc/objc.h}: this is the basic Objective-C header file,
65 defining the basic Objective-C types such as @code{id}, @code{Class}
66 and @code{BOOL}. You have to include this header to do almost
67 anything with Objective-C.
70 @file{objc/runtime.h}: this header declares most of the public runtime
71 API functions allowing you to inspect and manipulate the Objective-C
72 runtime data structures. These functions are fairly standardized
73 across Objective-C runtimes and are almost identical to the Apple/NeXT
74 Objective-C runtime ones. It does not declare functions in some
75 specialized areas (constructing and forwarding message invocations,
76 threading) which are in the other headers below. You have to include
77 @file{objc/objc.h} and @file{objc/runtime.h} to use any of the
78 functions, such as @code{class_getName()}, declared in
79 @file{objc/runtime.h}.
82 @file{objc/message.h}: this header declares public functions used to
83 construct, deconstruct and forward message invocations. Because
84 messaging is done in quite a different way on different runtimes,
85 functions in this header are specific to the GNU Objective-C runtime
89 @file{objc/objc-exception.h}: this header declares some public
90 functions related to Objective-C exceptions. For example functions in
91 this header allow you to throw an Objective-C exception from plain
95 @file{objc/objc-sync.h}: this header declares some public functions
96 related to the Objective-C @code{@@synchronized()} syntax, allowing
97 you to emulate an Objective-C @code{@@synchronized()} block in plain
101 @file{objc/thr.h}: this header declares a public runtime API threading
102 layer that is only provided by the GNU Objective-C runtime. It
103 declares functions such as @code{objc_mutex_lock()}, which provide a
104 platform-independent set of threading functions.
108 The header files contain detailed documentation for each function in
109 the GNU Objective-C runtime API.
111 @c =========================================================================
112 @node Traditional GNU Objective-C runtime API
113 @subsection Traditional GNU Objective-C runtime API
115 The GNU Objective-C runtime used to provide a different API, which we
116 call the ``traditional'' GNU Objective-C runtime API. Functions
117 belonging to this API are easy to recognize because they use a
118 different naming convention, such as @code{class_get_super_class()}
119 (traditional API) instead of @code{class_getSuperclass()} (modern
120 API). Software using this API includes the file
121 @file{objc/objc-api.h} where it is declared.
123 The traditional API is deprecated but it is still supported in this
124 release of the runtime; you can access it as usual by including
125 @file{objc/objc-api.h}.
127 If you are using the traditional API you are urged to upgrade your
128 software to use the modern API because the traditional API requires
129 access to private runtime internals to do anything serious with it;
130 for this reason, there is no guarantee that future releases of the GNU
131 Objective-C runtime library will be able to provide a fully compatible
132 @file{objc/objc-api.h} as the private runtime internals change. It is
133 expected that the next release will hide a number of runtime internals
134 making the traditional API nominally supported but fairly useless
135 beyond very simple use cases.
137 Finally, you can not include both @file{objc/objc-api.h} and
138 @file{objc/runtime.h} at the same time. The traditional and modern
139 APIs unfortunately have some conflicting declarations (such as the one
140 for @code{Method}) and can not be used at the same time.
142 @c =========================================================================
143 @node Executing code before main
144 @section @code{+load}: Executing code before main
146 This section is specific for the GNU Objective-C runtime. If you are
147 using a different runtime, you can skip it.
149 The GNU Objective-C runtime provides a way that allows you to execute
150 code before the execution of the program enters the @code{main}
151 function. The code is executed on a per-class and a per-category basis,
152 through a special class method @code{+load}.
154 This facility is very useful if you want to initialize global variables
155 which can be accessed by the program directly, without sending a message
156 to the class first. The usual way to initialize global variables, in the
157 @code{+initialize} method, might not be useful because
158 @code{+initialize} is only called when the first message is sent to a
159 class object, which in some cases could be too late.
161 Suppose for example you have a @code{FileStream} class that declares
162 @code{Stdin}, @code{Stdout} and @code{Stderr} as global variables, like
167 FileStream *Stdin = nil;
168 FileStream *Stdout = nil;
169 FileStream *Stderr = nil;
171 @@implementation FileStream
175 Stdin = [[FileStream new] initWithFd:0];
176 Stdout = [[FileStream new] initWithFd:1];
177 Stderr = [[FileStream new] initWithFd:2];
180 /* @r{Other methods here} */
185 In this example, the initialization of @code{Stdin}, @code{Stdout} and
186 @code{Stderr} in @code{+initialize} occurs too late. The programmer can
187 send a message to one of these objects before the variables are actually
188 initialized, thus sending messages to the @code{nil} object. The
189 @code{+initialize} method which actually initializes the global
190 variables is not invoked until the first message is sent to the class
191 object. The solution would require these variables to be initialized
192 just before entering @code{main}.
194 The correct solution of the above problem is to use the @code{+load}
195 method instead of @code{+initialize}:
199 @@implementation FileStream
203 Stdin = [[FileStream new] initWithFd:0];
204 Stdout = [[FileStream new] initWithFd:1];
205 Stderr = [[FileStream new] initWithFd:2];
208 /* @r{Other methods here} */
213 The @code{+load} is a method that is not overridden by categories. If a
214 class and a category of it both implement @code{+load}, both methods are
215 invoked. This allows some additional initializations to be performed in
218 This mechanism is not intended to be a replacement for @code{+initialize}.
219 You should be aware of its limitations when you decide to use it
220 instead of @code{+initialize}.
223 * What you can and what you cannot do in +load::
227 @node What you can and what you cannot do in +load
228 @subsection What you can and what you cannot do in @code{+load}
230 @code{+load} is to be used only as a last resort. Because it is
231 executed very early, most of the Objective-C runtime machinery will
232 not be ready when @code{+load} is executed; hence @code{+load} works
233 best for executing C code that is independent on the Objective-C
236 The @code{+load} implementation in the GNU runtime guarantees you the
242 you can write whatever C code you like;
245 you can allocate and send messages to objects whose class is implemented
249 the @code{+load} implementation of all super classes of a class are
250 executed before the @code{+load} of that class is executed;
253 the @code{+load} implementation of a class is executed before the
254 @code{+load} implementation of any category.
258 In particular, the following things, even if they can work in a
259 particular case, are not guaranteed:
264 allocation of or sending messages to arbitrary objects;
267 allocation of or sending messages to objects whose classes have a
268 category implemented in the same file;
271 sending messages to Objective-C constant strings (@code{@@"this is a
276 You should make no assumptions about receiving @code{+load} in sibling
277 classes when you write @code{+load} of a class. The order in which
278 sibling classes receive @code{+load} is not guaranteed.
280 The order in which @code{+load} and @code{+initialize} are called could
281 be problematic if this matters. If you don't allocate objects inside
282 @code{+load}, it is guaranteed that @code{+load} is called before
283 @code{+initialize}. If you create an object inside @code{+load} the
284 @code{+initialize} method of object's class is invoked even if
285 @code{+load} was not invoked. Note if you explicitly call @code{+load}
286 on a class, @code{+initialize} will be called first. To avoid possible
287 problems try to implement only one of these methods.
289 The @code{+load} method is also invoked when a bundle is dynamically
290 loaded into your running program. This happens automatically without any
291 intervening operation from you. When you write bundles and you need to
292 write @code{+load} you can safely create and send messages to objects whose
293 classes already exist in the running program. The same restrictions as
294 above apply to classes defined in bundle.
299 @section Type encoding
301 This is an advanced section. Type encodings are used extensively by
302 the compiler and by the runtime, but you generally do not need to know
303 about them to use Objective-C.
305 The Objective-C compiler generates type encodings for all the types.
306 These type encodings are used at runtime to find out information about
307 selectors and methods and about objects and classes.
309 The types are encoded in the following way:
313 @multitable @columnfractions .25 .75
318 @item @code{unsigned char}
322 @item @code{unsigned short}
326 @item @code{unsigned int}
330 @item @code{unsigned long}
332 @item @code{long long}
334 @item @code{unsigned long long}
340 @item @code{long double}
353 @tab an @code{enum} is encoded exactly as the integer type that the compiler uses for it, which depends on the enumeration
354 values. Often the compiler users @code{unsigned int}, which is then encoded as @code{I}.
358 @tab @code{j} followed by the inner type. For example @code{_Complex double} is encoded as "jd".
360 @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)
365 The encoding of bit-fields has changed to allow bit-fields to be
366 properly handled by the runtime functions that compute sizes and
367 alignments of types that contain bit-fields. The previous encoding
368 contained only the size of the bit-field. Using only this information
369 it is not possible to reliably compute the size occupied by the
370 bit-field. This is very important in the presence of the Boehm's
371 garbage collector because the objects are allocated using the typed
372 memory facility available in this collector. The typed memory
373 allocation requires information about where the pointers are located
376 The position in the bit-field is the position, counting in bits, of the
377 bit closest to the beginning of the structure.
379 The non-atomic types are encoded as follows:
383 @multitable @columnfractions .2 .8
385 @tab @samp{^} followed by the pointed type.
387 @tab @samp{[} followed by the number of elements in the array followed by the type of the elements followed by @samp{]}
389 @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 @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 @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{]}
396 Here are some types and their encodings, as they are generated by the
397 compiler on an i386 machine:
401 @multitable @columnfractions .25 .75
402 @item Objective-C type
403 @tab Compiler encoding
419 @tab @code{@{?=i[3f]b128i3b131i2c@}}
422 int a __attribute__ ((vector_size (16)));
424 @tab @code{![16,16i]} (alignment would depend on the machine)
429 In addition to the types the compiler also encodes the type
430 specifiers. The table below describes the encoding of the current
431 Objective-C type specifiers:
435 @multitable @columnfractions .25 .75
456 The type specifiers are encoded just before the type. Unlike types
457 however, the type specifiers are only encoded when they appear in method
460 Note how @code{const} interacts with pointers:
464 @multitable @columnfractions .25 .75
465 @item Objective-C type
466 @tab Compiler encoding
486 @code{const int*} is a pointer to a @code{const int}, and so is
487 encoded as @code{^ri}. @code{int* const}, instead, is a @code{const}
488 pointer to an @code{int}, and so is encoded as @code{r^i}.
490 Finally, there is a complication when encoding @code{const char *}
491 versus @code{char * const}. Because @code{char *} is encoded as
492 @code{*} and not as @code{^c}, there is no way to express the fact
493 that @code{r} applies to the pointer or to the pointee.
495 Hence, it is assumed as a convention that @code{r*} means @code{const
496 char *} (since it is what is most often meant), and there is no way to
497 encode @code{char *const}. @code{char *const} would simply be encoded
498 as @code{*}, and the @code{const} is lost.
501 * Legacy type encoding::
503 * Method signatures::
506 @node Legacy type encoding
507 @subsection Legacy type encoding
509 Unfortunately, historically GCC used to have a number of bugs in its
510 encoding code. The NeXT runtime expects GCC to emit type encodings in
511 this historical format (compatible with GCC-3.3), so when using the
512 NeXT runtime, GCC will introduce on purpose a number of incorrect
518 the read-only qualifier of the pointee gets emitted before the '^'.
519 The read-only qualifier of the pointer itself gets ignored, unless it
520 is a typedef. Also, the 'r' is only emitted for the outermost type.
523 32-bit longs are encoded as 'l' or 'L', but not always. For typedefs,
524 the compiler uses 'i' or 'I' instead if encoding a struct field or a
528 @code{enum}s are always encoded as 'i' (int) even if they are actually
533 In addition to that, the NeXT runtime uses a different encoding for
534 bitfields. It encodes them as @code{b} followed by the size, without
535 a bit offset or the underlying field type.
540 GNU Objective-C supports the @code{@@encode} syntax that allows you to
541 create a type encoding from a C/Objective-C type. For example,
542 @code{@@encode(int)} is compiled by the compiler into @code{"i"}.
544 @code{@@encode} does not support type qualifiers other than
545 @code{const}. For example, @code{@@encode(const char*)} is valid and
546 is compiled into @code{"r*"}, while @code{@@encode(bycopy char *)} is
547 invalid and will cause a compilation error.
549 @node Method signatures
550 @subsection Method signatures
552 This section documents the encoding of method types, which is rarely
553 needed to use Objective-C. You should skip it at a first reading; the
554 runtime provides functions that will work on methods and can walk
555 through the list of parameters and interpret them for you. These
556 functions are part of the public ``API'' and are the preferred way to
557 interact with method signatures from user code.
559 But if you need to debug a problem with method signatures and need to
560 know how they are implemented (ie, the ``ABI''), read on.
562 Methods have their ``signature'' encoded and made available to the
563 runtime. The ``signature'' encodes all the information required to
564 dynamically build invocations of the method at runtime: return type
567 The ``signature'' is a null-terminated string, composed of the following:
572 The return type, including type qualifiers. For example, a method
573 returning @code{int} would have @code{i} here.
576 The total size (in bytes) required to pass all the parameters. This
577 includes the two hidden parameters (the object @code{self} and the
578 method selector @code{_cmd}).
581 Each argument, with the type encoding, followed by the offset (in
582 bytes) of the argument in the list of parameters.
586 For example, a method with no arguments and returning @code{int} would
587 have the signature @code{i8@@0:4} if the size of a pointer is 4. The
588 signature is interpreted as follows: the @code{i} is the return type
589 (an @code{int}), the @code{8} is the total size of the parameters in
590 bytes (two pointers each of size 4), the @code{@@0} is the first
591 parameter (an object at byte offset @code{0}) and @code{:4} is the
592 second parameter (a @code{SEL} at byte offset @code{4}).
594 You can easily find more examples by running the ``strings'' program
595 on an Objective-C object file compiled by GCC. You'll see a lot of
596 strings that look very much like @code{i8@@0:4}. They are signatures
597 of Objective-C methods.
600 @node Garbage Collection
601 @section Garbage Collection
603 This section is specific for the GNU Objective-C runtime. If you are
604 using a different runtime, you can skip it.
606 Support for garbage collection with the GNU runtime has been added by
607 using a powerful conservative garbage collector, known as the
608 Boehm-Demers-Weiser conservative garbage collector.
610 To enable the support for it you have to configure the compiler using
611 an additional argument, @w{@option{--enable-objc-gc}}. This will
612 build the boehm-gc library, and build an additional runtime library
613 which has several enhancements to support the garbage collector. The
614 new library has a new name, @file{libobjc_gc.a} to not conflict with
615 the non-garbage-collected library.
617 When the garbage collector is used, the objects are allocated using the
618 so-called typed memory allocation mechanism available in the
619 Boehm-Demers-Weiser collector. This mode requires precise information on
620 where pointers are located inside objects. This information is computed
621 once per class, immediately after the class has been initialized.
623 There is a new runtime function @code{class_ivar_set_gcinvisible()}
624 which can be used to declare a so-called @dfn{weak pointer}
625 reference. Such a pointer is basically hidden for the garbage collector;
626 this can be useful in certain situations, especially when you want to
627 keep track of the allocated objects, yet allow them to be
628 collected. This kind of pointers can only be members of objects, you
629 cannot declare a global pointer as a weak reference. Every type which is
630 a pointer type can be declared a weak pointer, including @code{id},
631 @code{Class} and @code{SEL}.
633 Here is an example of how to use this feature. Suppose you want to
634 implement a class whose instances hold a weak pointer reference; the
635 following class does this:
639 @@interface WeakPointer : Object
641 const void* weakPointer;
644 - initWithPointer:(const void*)p;
645 - (const void*)weakPointer;
649 @@implementation WeakPointer
653 class_ivar_set_gcinvisible (self, "weakPointer", YES);
656 - initWithPointer:(const void*)p
662 - (const void*)weakPointer
671 Weak pointers are supported through a new type character specifier
672 represented by the @samp{!} character. The
673 @code{class_ivar_set_gcinvisible()} function adds or removes this
674 specifier to the string type description of the instance variable named
677 @c =========================================================================
678 @node Constant string objects
679 @section Constant string objects
681 GNU Objective-C provides constant string objects that are generated
682 directly by the compiler. You declare a constant string object by
683 prefixing a C constant string with the character @samp{@@}:
686 id myString = @@"this is a constant string object";
689 The constant string objects are by default instances of the
690 @code{NXConstantString} class which is provided by the GNU Objective-C
691 runtime. To get the definition of this class you must include the
692 @file{objc/NXConstStr.h} header file.
694 User defined libraries may want to implement their own constant string
695 class. To be able to support them, the GNU Objective-C compiler provides
696 a new command line options @option{-fconstant-string-class=@var{class-name}}.
697 The provided class should adhere to a strict structure, the same
698 as @code{NXConstantString}'s structure:
702 @@interface MyConstantStringClass
712 @code{NXConstantString} inherits from @code{Object}; user class
713 libraries may choose to inherit the customized constant string class
714 from a different class than @code{Object}. There is no requirement in
715 the methods the constant string class has to implement, but the final
716 ivar layout of the class must be the compatible with the given
719 When the compiler creates the statically allocated constant string
720 object, the @code{c_string} field will be filled by the compiler with
721 the string; the @code{length} field will be filled by the compiler with
722 the string length; the @code{isa} pointer will be filled with
723 @code{NULL} by the compiler, and it will later be fixed up automatically
724 at runtime by the GNU Objective-C runtime library to point to the class
725 which was set by the @option{-fconstant-string-class} option when the
726 object file is loaded (if you wonder how it works behind the scenes, the
727 name of the class to use, and the list of static objects to fixup, are
728 stored by the compiler in the object file in a place where the GNU
729 runtime library will find them at runtime).
731 As a result, when a file is compiled with the
732 @option{-fconstant-string-class} option, all the constant string objects
733 will be instances of the class specified as argument to this option. It
734 is possible to have multiple compilation units referring to different
735 constant string classes, neither the compiler nor the linker impose any
736 restrictions in doing this.
738 @c =========================================================================
739 @node compatibility_alias
740 @section compatibility_alias
742 The keyword @code{@@compatibility_alias} allows you to define a class name
743 as equivalent to another class name. For example:
746 @@compatibility_alias WOApplication GSWApplication;
749 tells the compiler that each time it encounters @code{WOApplication} as
750 a class name, it should replace it with @code{GSWApplication} (that is,
751 @code{WOApplication} is just an alias for @code{GSWApplication}).
753 There are some constraints on how this can be used---
757 @item @code{WOApplication} (the alias) must not be an existing class;
759 @item @code{GSWApplication} (the real class) must be an existing class.
763 @c =========================================================================
767 GNU Objective-C provides exception support built into the language, as
768 in the following example:
776 @@catch (AnObjCClass *exc) @{
783 @@catch (AnotherClass *exc) @{
786 @@catch (id allOthers) @{
796 The @code{@@throw} statement may appear anywhere in an Objective-C or
797 Objective-C++ program; when used inside of a @code{@@catch} block, the
798 @code{@@throw} may appear without an argument (as shown above), in
799 which case the object caught by the @code{@@catch} will be rethrown.
801 Note that only (pointers to) Objective-C objects may be thrown and
802 caught using this scheme. When an object is thrown, it will be caught
803 by the nearest @code{@@catch} clause capable of handling objects of
804 that type, analogously to how @code{catch} blocks work in C++ and
805 Java. A @code{@@catch(id @dots{})} clause (as shown above) may also
806 be provided to catch any and all Objective-C exceptions not caught by
807 previous @code{@@catch} clauses (if any).
809 The @code{@@finally} clause, if present, will be executed upon exit
810 from the immediately preceding @code{@@try @dots{} @@catch} section.
811 This will happen regardless of whether any exceptions are thrown,
812 caught or rethrown inside the @code{@@try @dots{} @@catch} section,
813 analogously to the behavior of the @code{finally} clause in Java.
815 There are several caveats to using the new exception mechanism:
819 The @option{-fobjc-exceptions} command line option must be used when
820 compiling Objective-C files that use exceptions.
823 With the GNU runtime, exceptions are always implemented as ``native''
824 exceptions and it is recommended that the @option{-fexceptions} and
825 @option{-shared-libgcc} options are used when linking.
828 With the NeXT runtime, although currently designed to be binary
829 compatible with @code{NS_HANDLER}-style idioms provided by the
830 @code{NSException} class, the new exceptions can only be used on Mac
831 OS X 10.3 (Panther) and later systems, due to additional functionality
832 needed in the NeXT Objective-C runtime.
835 As mentioned above, the new exceptions do not support handling
836 types other than Objective-C objects. Furthermore, when used from
837 Objective-C++, the Objective-C exception model does not interoperate with C++
838 exceptions at this time. This means you cannot @code{@@throw} an exception
839 from Objective-C and @code{catch} it in C++, or vice versa
840 (i.e., @code{throw @dots{} @@catch}).
843 @c =========================================================================
844 @node Synchronization
845 @section Synchronization
847 GNU Objective-C provides support for synchronized blocks:
850 @@synchronized (ObjCClass *guard) @{
855 Upon entering the @code{@@synchronized} block, a thread of execution
856 shall first check whether a lock has been placed on the corresponding
857 @code{guard} object by another thread. If it has, the current thread
858 shall wait until the other thread relinquishes its lock. Once
859 @code{guard} becomes available, the current thread will place its own
860 lock on it, execute the code contained in the @code{@@synchronized}
861 block, and finally relinquish the lock (thereby making @code{guard}
862 available to other threads).
864 Unlike Java, Objective-C does not allow for entire methods to be
865 marked @code{@@synchronized}. Note that throwing exceptions out of
866 @code{@@synchronized} blocks is allowed, and will cause the guarding
867 object to be unlocked properly.
869 Because of the interactions between synchronization and exception
870 handling, you can only use @code{@@synchronized} when compiling with
871 exceptions enabled, that is with the command line option
872 @option{-fobjc-exceptions}.
875 @c =========================================================================
876 @node Fast enumeration
877 @section Fast enumeration
880 * Using fast enumeration::
881 * c99-like fast enumeration syntax::
882 * Fast enumeration details::
883 * Fast enumeration protocol::
886 @c ================================
887 @node Using fast enumeration
888 @subsection Using fast enumeration
890 GNU Objective-C provides support for the fast enumeration syntax:
896 for (object in array)
898 /* Do something with 'object' */
902 @code{array} needs to be an Objective-C object (usually a collection
903 object, for example an array, a dictionary or a set) which implements
904 the ``Fast Enumeration Protocol'' (see below). If you are using a
905 Foundation library such as GNUstep Base or Apple Cocoa Foundation, all
906 collection objects in the library implement this protocol and can be
909 The code above would iterate over all objects in @code{array}. For
910 each of them, it assigns it to @code{object}, then executes the
911 @code{Do something with 'object'} statements.
913 Here is a fully worked-out example using a Foundation library (which
914 provides the implementation of @code{NSArray}, @code{NSString} and
918 NSArray *array = [NSArray arrayWithObjects: @@"1", @@"2", @@"3", nil];
921 for (object in array)
922 NSLog (@@"Iterating over %@@", object);
926 @c ================================
927 @node c99-like fast enumeration syntax
928 @subsection c99-like fast enumeration syntax
930 A c99-like declaration syntax is also allowed:
935 for (id object in array)
937 /* Do something with 'object' */
941 this is completely equivalent to:
948 for (object in array)
950 /* Do something with 'object' */
955 but can save some typing.
957 Note that the option @option{-std=c99} is not required to allow this
958 syntax in Objective-C.
960 @c ================================
961 @node Fast enumeration details
962 @subsection Fast enumeration details
964 Here is a more technical description with the gory details. Consider the code
967 for (@var{object expression} in @var{collection expression})
973 here is what happens when you run it:
977 @code{@var{collection expression}} is evaluated exactly once and the
978 result is used as the collection object to iterate over. This means
979 it is safe to write code such as @code{for (object in [NSDictionary
980 keyEnumerator]) @dots{}}.
983 the iteration is implemented by the compiler by repeatedly getting
984 batches of objects from the collection object using the fast
985 enumeration protocol (see below), then iterating over all objects in
986 the batch. This is faster than a normal enumeration where objects are
987 retrieved one by one (hence the name ``fast enumeration'').
990 if there are no objects in the collection, then
991 @code{@var{object expression}} is set to @code{nil} and the loop
992 immediately terminates.
995 if there are objects in the collection, then for each object in the
996 collection (in the order they are returned) @code{@var{object expression}}
997 is set to the object, then @code{@var{statements}} are executed.
1000 @code{@var{statements}} can contain @code{break} and @code{continue}
1001 commands, which will abort the iteration or skip to the next loop
1002 iteration as expected.
1005 when the iteration ends because there are no more objects to iterate
1006 over, @code{@var{object expression}} is set to @code{nil}. This allows
1007 you to determine whether the iteration finished because a @code{break}
1008 command was used (in which case @code{@var{object expression}} will remain
1009 set to the last object that was iterated over) or because it iterated
1010 over all the objects (in which case @code{@var{object expression}} will be
1014 @code{@var{statements}} must not make any changes to the collection
1015 object; if they do, it is a hard error and the fast enumeration
1016 terminates by invoking @code{objc_enumerationMutation}, a runtime
1017 function that normally aborts the program but which can be customized
1018 by Foundation libraries via @code{objc_set_mutation_handler} to do
1019 something different, such as raising an exception.
1023 @c ================================
1024 @node Fast enumeration protocol
1025 @subsection Fast enumeration protocol
1027 If you want your own collection object to be usable with fast
1028 enumeration, you need to have it implement the method
1031 - (unsigned long) countByEnumeratingWithState: (NSFastEnumerationState *)state
1032 objects: (id *)objects
1033 count: (unsigneld long)len;
1036 where @code{NSFastEnumerationState} must be defined in your code as follows:
1041 unsigned long state;
1043 unsigned long *mutationsPtr;
1044 unsigned long extra[5];
1045 @} NSFastEnumerationState;
1048 If no @code{NSFastEnumerationState} is defined in your code, the
1049 compiler will automatically replace @code{NSFastEnumerationState *}
1050 with @code{struct __objcFastEnumerationState *}, where that type is
1051 silently defined by the compiler in an identical way. This can be
1052 confusing and we recommend that you define
1053 @code{NSFastEnumerationState} (as shown above) instead.
1055 The method is called repeatedly during a fast enumeration to retrieve
1056 batches of objects. Each invocation of the method should retrieve the
1057 next batch of objects.
1059 The return value of the method is the number of objects in the current
1060 batch; this should not exceed @code{len}, which is the maximum size of
1061 a batch as requested by the caller. The batch itself is returned in
1062 the @code{itemsPtr} field of the @code{NSFastEnumerationState} struct.
1064 To help with returning the objects, the @code{objects} array is a C
1065 array preallocated by the caller (on the stack) of size @code{len}.
1066 In many cases you can put the objects you want to return in that
1067 @code{objects} array, then do @code{itemsPtr = objects}. But you
1068 don't have to; if your collection already has the objects to return in
1069 some form of C array, it could return them from there instead.
1071 The @code{state} and @code{extra} fields of the
1072 @code{NSFastEnumerationState} structure allows your collection object
1073 to keep track of the state of the enumeration. In a simple array
1074 implementation, @code{state} may keep track of the index of the last
1075 object that was returned, and @code{extra} may be unused.
1077 The @code{mutationsPtr} field of the @code{NSFastEnumerationState} is
1078 used to keep track of mutations. It should point to a number; before
1079 working on each object, the fast enumeration loop will check that this
1080 number has not changed. If it has, a mutation has happened and the
1081 fast enumeration will abort. So, @code{mutationsPtr} could be set to
1082 point to some sort of version number of your collection, which is
1083 increased by one every time there is a change (for example when an
1084 object is added or removed). Or, if you are content with less strict
1085 mutation checks, it could point to the number of objects in your
1086 collection or some other value that can be checked to perform an
1087 approximate check that the collection has not been mutated.
1089 Finally, note how we declared the @code{len} argument and the return
1090 value to be of type @code{unsigned long}. They could also be declared
1091 to be of type @code{unsigned int} and everything would still work.
1093 @c =========================================================================
1094 @node Messaging with the GNU Objective-C runtime
1095 @section Messaging with the GNU Objective-C runtime
1097 This section is specific for the GNU Objective-C runtime. If you are
1098 using a different runtime, you can skip it.
1100 The implementation of messaging in the GNU Objective-C runtime is
1101 designed to be portable, and so is based on standard C.
1103 Sending a message in the GNU Objective-C runtime is composed of two
1104 separate steps. First, there is a call to the lookup function,
1105 @code{objc_msg_lookup ()} (or, in the case of messages to super,
1106 @code{objc_msg_lookup_super ()}). This runtime function takes as
1107 argument the receiver and the selector of the method to be called; it
1108 returns the @code{IMP}, that is a pointer to the function implementing
1109 the method. The second step of method invocation consists of casting
1110 this pointer function to the appropriate function pointer type, and
1111 calling the function pointed to it with the right arguments.
1113 For example, when the compiler encounters a method invocation such as
1114 @code{[object init]}, it compiles it into a call to
1115 @code{objc_msg_lookup (object, @@selector(init))} followed by a cast
1116 of the returned value to the appropriate function pointer type, and
1120 * Dynamically registering methods::
1124 @c =========================================================================
1125 @node Dynamically registering methods
1126 @subsection Dynamically registering methods
1128 If @code{objc_msg_lookup()} does not find a suitable method
1129 implementation, because the receiver does not implement the required
1130 method, it tries to see if the class can dynamically register the
1133 To do so, the runtime checks if the class of the receiver implements
1137 + (BOOL) resolveInstanceMethod: (SEL)selector;
1140 in the case of an instance method, or
1143 + (BOOL) resolveClassMethod: (SEL)selector;
1146 in the case of a class method. If the class implements it, the
1147 runtime invokes it, passing as argument the selector of the original
1148 method, and if it returns @code{YES}, the runtime tries the lookup
1149 again, which could now succeed if a matching method was added
1150 dynamically by @code{+resolveInstanceMethod:} or
1151 @code{+resolveClassMethod:}.
1153 This allows classes to dynamically register methods (by adding them to
1154 the class using @code{class_addMethod}) when they are first called.
1155 To do so, a class should implement @code{+resolveInstanceMethod:} (or,
1156 depending on the case, @code{+resolveClassMethod:}) and have it
1157 recognize the selectors of methods that can be registered dynamically
1158 at runtime, register them, and return @code{YES}. It should return
1159 @code{NO} for methods that it does not dynamically registered at
1162 If @code{+resolveInstanceMethod:} (or @code{+resolveClassMethod:}) is
1163 not implemented or returns @code{NO}, the runtime then tries the
1166 Support for @code{+resolveInstanceMethod:} and
1167 @code{resolveClassMethod:} was added to the GNU Objective-C runtime in
1170 @c =========================================================================
1171 @node Forwarding hook
1172 @subsection Forwarding hook
1174 The GNU Objective-C runtime provides a hook, called
1175 @code{__objc_msg_forward2}, which is called by
1176 @code{objc_msg_lookup()} when it can't find a method implementation in
1177 the runtime tables and after calling @code{+resolveInstanceMethod:}
1178 and @code{+resolveClassMethod:} has been attempted and did not succeed
1179 in dynamically registering the method.
1181 To configure the hook, you set the global variable
1182 @code{__objc_msg_foward2} to a function with the same argument and
1183 return types of @code{objc_msg_lookup()}. When
1184 @code{objc_msg_lookup()} can not find a method implementation, it
1185 invokes the hook function you provided to get a method implementation
1186 to return. So, in practice @code{__objc_msg_forward2} allows you to
1187 extend @code{objc_msg_lookup()} by adding some custom code that is
1188 called to do a further lookup when no standard method implementation
1189 can be found using the normal lookup.
1191 This hook is generally reserved for ``Foundation'' libraries such as
1192 GNUstep Base, which use it to implement their high-level method
1193 forwarding API, typically based around the @code{forwardInvocation:}
1194 method. So, unless you are implementing your own ``Foundation''
1195 library, you should not set this hook.
1197 In a typical forwarding implementation, the @code{__objc_msg_forward2}
1198 hook function determines the argument and return type of the method
1199 that is being looked up, and then creates a function that takes these
1200 arguments and has that return type, and returns it to the caller.
1201 Creating this function is non-trivial and is typically performed using
1202 a dedicated library such as @code{libffi}.
1204 The forwarding method implementation thus created is returned by
1205 @code{objc_msg_lookup()} and is executed as if it was a normal method
1206 implementation. When the forwarding method implementation is called,
1207 it is usually expected to pack all arguments into some sort of object
1208 (typically, an @code{NSInvocation} in a ``Foundation'' library), and
1209 hand it over to the programmer (@code{forwardInvocation:}) who is then
1210 allowed to manipulate the method invocation using a high-level API
1211 provided by the ``Foundation'' library. For example, the programmer
1212 may want to examine the method invocation arguments and name and
1213 potentially change them before forwarding the method invocation to one
1214 or more local objects (@code{performInvocation:}) or even to remote
1215 objects (by using Distributed Objects or some other mechanism). When
1216 all this completes, the return value is passed back and must be
1217 returned correctly to the original caller.
1219 Note that the GNU Objective-C runtime currently provides no support
1220 for method forwarding or method invocations other than the
1221 @code{__objc_msg_forward2} hook.
1223 If the forwarding hook does not exist or returns @code{NULL}, the
1224 runtime currently attempts forwarding using an older, deprecated API,
1225 and if that fails, it aborts the program. In future versions of the
1226 GNU Objective-C runtime, the runtime will immediately abort.