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::
27 @c =========================================================================
28 @node GNU Objective-C runtime API
29 @section GNU Objective-C runtime API
31 This section is specific for the GNU Objective-C runtime. If you are
32 using a different runtime, you can skip it.
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
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.
47 * Modern GNU Objective-C runtime API::
48 * Traditional GNU Objective-C runtime API::
51 @c =========================================================================
52 @node Modern GNU Objective-C runtime API
53 @subsection Modern GNU Objective-C runtime API
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
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.
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}.
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
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
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
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.
107 @c =========================================================================
108 @node Traditional GNU Objective-C runtime API
109 @subsection Traditional GNU Objective-C runtime API
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.
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}.
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.
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.
138 @c =========================================================================
139 @node Executing code before main
140 @section @code{+load}: Executing code before main
142 This section is specific for the GNU Objective-C runtime. If you are
143 using a different runtime, you can skip it.
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}.
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.
157 Suppose for example you have a @code{FileStream} class that declares
158 @code{Stdin}, @code{Stdout} and @code{Stderr} as global variables, like
163 FileStream *Stdin = nil;
164 FileStream *Stdout = nil;
165 FileStream *Stderr = nil;
167 @@implementation FileStream
171 Stdin = [[FileStream new] initWithFd:0];
172 Stdout = [[FileStream new] initWithFd:1];
173 Stderr = [[FileStream new] initWithFd:2];
176 /* @r{Other methods here} */
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}.
190 The correct solution of the above problem is to use the @code{+load}
191 method instead of @code{+initialize}:
195 @@implementation FileStream
199 Stdin = [[FileStream new] initWithFd:0];
200 Stdout = [[FileStream new] initWithFd:1];
201 Stderr = [[FileStream new] initWithFd:2];
204 /* @r{Other methods here} */
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
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}.
219 * What you can and what you cannot do in +load::
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}
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
232 The @code{+load} implementation in the GNU runtime guarantees you the
238 you can write whatever C code you like;
241 you can allocate and send messages to objects whose class is implemented
245 the @code{+load} implementation of all super classes of a class are
246 executed before the @code{+load} of that class is executed;
249 the @code{+load} implementation of a class is executed before the
250 @code{+load} implementation of any category.
254 In particular, the following things, even if they can work in a
255 particular case, are not guaranteed:
260 allocation of or sending messages to arbitrary objects;
263 allocation of or sending messages to objects whose classes have a
264 category implemented in the same file;
267 sending messages to Objective-C constant strings (@code{@@"this is a
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.
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.
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.
295 @section Type encoding
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.
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.
305 The types are encoded in the following way:
309 @multitable @columnfractions .25 .75
314 @item @code{unsigned char}
318 @item @code{unsigned short}
322 @item @code{unsigned int}
326 @item @code{unsigned long}
328 @item @code{long long}
330 @item @code{unsigned long long}
336 @item @code{long double}
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}.
354 @tab @code{j} followed by the inner type. For example @code{_Complex double} is encoded as "jd".
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)
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
372 The position in the bit-field is the position, counting in bits, of the
373 bit closest to the beginning of the structure.
375 The non-atomic types are encoded as follows:
379 @multitable @columnfractions .2 .8
381 @tab @samp{^} followed by the pointed type.
383 @tab @samp{[} followed by the number of elements in the array followed by the type of the elements followed by @samp{]}
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{@}}
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{)}
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{]}
392 Here are some types and their encodings, as they are generated by the
393 compiler on an i386 machine:
397 @multitable @columnfractions .25 .75
398 @item Objective-C type
399 @tab Compiler encoding
415 @tab @code{@{?=i[3f]b128i3b131i2c@}}
418 int a __attribute__ ((vector_size (16)));
420 @tab @code{![16,16i]} (alignment would depend on the machine)
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:
431 @multitable @columnfractions .25 .75
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
456 Note how @code{const} interacts with pointers:
460 @multitable @columnfractions .25 .75
461 @item Objective-C type
462 @tab Compiler encoding
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}.
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.
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.
497 * Legacy type encoding::
499 * Method signatures::
502 @node Legacy type encoding
503 @subsection Legacy type encoding
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
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.
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
524 @code{enum}s are always encoded as 'i' (int) even if they are actually
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.
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"}.
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.
545 @node Method signatures
546 @subsection Method signatures
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.
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.
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
563 The ``signature'' is a null-terminated string, composed of the following:
568 The return type, including type qualifiers. For example, a method
569 returning @code{int} would have @code{i} here.
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}).
577 Each argument, with the type encoding, followed by the offset (in
578 bytes) of the argument in the list of parameters.
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}).
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.
596 @node Garbage Collection
597 @section Garbage Collection
599 This section is specific for the GNU Objective-C runtime. If you are
600 using a different runtime, you can skip it.
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.
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.
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.
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}.
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:
635 @@interface WeakPointer : Object
637 const void* weakPointer;
640 - initWithPointer:(const void*)p;
641 - (const void*)weakPointer;
645 @@implementation WeakPointer
649 class_ivar_set_gcinvisible (self, "weakPointer", YES);
652 - initWithPointer:(const void*)p
658 - (const void*)weakPointer
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
673 @c =========================================================================
674 @node Constant string objects
675 @section Constant string objects
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{@@}:
682 id myString = @@"this is a constant string object";
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.
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:
698 @@interface MyConstantStringClass
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
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).
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.
734 @c =========================================================================
735 @node compatibility_alias
736 @section compatibility_alias
738 The keyword @code{@@compatibility_alias} allows you to define a class name
739 as equivalent to another class name. For example:
742 @@compatibility_alias WOApplication GSWApplication;
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}).
749 There are some constraints on how this can be used---
753 @item @code{WOApplication} (the alias) must not be an existing class;
755 @item @code{GSWApplication} (the real class) must be an existing class.
759 @c =========================================================================
763 GNU Objective-C provides exception support built into the language, as
764 in the following example:
772 @@catch (AnObjCClass *exc) @{
779 @@catch (AnotherClass *exc) @{
782 @@catch (id allOthers) @{
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.
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).
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.
811 There are several caveats to using the new exception mechanism:
815 The @option{-fobjc-exceptions} command line option must be used when
816 compiling Objective-C files that use exceptions.
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.
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.
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}).
839 @c =========================================================================
840 @node Synchronization
841 @section Synchronization
843 GNU Objective-C provides support for synchronized blocks:
846 @@synchronized (ObjCClass *guard) @{
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).
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.
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}.
871 @c =========================================================================
872 @node Fast enumeration
873 @section Fast enumeration
876 * Using fast enumeration::
877 * c99-like fast enumeration syntax::
878 * Fast enumeration details::
879 * Fast enumeration protocol::
882 @c ================================
883 @node Using fast enumeration
884 @subsection Using fast enumeration
886 GNU Objective-C provides support for the fast enumeration syntax:
892 for (object in array)
894 /* Do something with 'object' */
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
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.
909 Here is a fully worked-out example using a Foundation library (which
910 provides the implementation of @code{NSArray}, @code{NSString} and
914 NSArray *array = [NSArray arrayWithObjects: @@"1", @@"2", @@"3", nil];
917 for (object in array)
918 NSLog (@@"Iterating over %@@", object);
922 @c ================================
923 @node c99-like fast enumeration syntax
924 @subsection c99-like fast enumeration syntax
926 A c99-like declaration syntax is also allowed:
931 for (id object in array)
933 /* Do something with 'object' */
937 this is completely equivalent to:
944 for (object in array)
946 /* Do something with 'object' */
951 but can save some typing.
953 Note that the option @option{-std=c99} is not required to allow this
954 syntax in Objective-C.
956 @c ================================
957 @node Fast enumeration details
958 @subsection Fast enumeration details
960 Here is a more technical description with the gory details. Consider the code
963 for (@var{object expression} in @var{collection expression})
969 here is what happens when you run it:
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{}}.
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'').
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.
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.
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.
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
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.
1019 @c ================================
1020 @node Fast enumeration protocol
1021 @subsection Fast enumeration protocol
1023 If you want your own collection object to be usable with fast
1024 enumeration, you need to have it implement the method
1027 - (unsigned long) countByEnumeratingWithState: (NSFastEnumerationState *)state
1028 objects: (id *)objects
1029 count: (unsigneld long)len;
1032 where @code{NSFastEnumerationState} must be defined in your code as follows:
1037 unsigned long state;
1039 unsigned long *mutationsPtr;
1040 unsigned long extra[5];
1041 @} NSFastEnumerationState;
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.
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.
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.
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.
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.
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.
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.