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