gcc: Garbage Collection
1
1 8.4 Garbage Collection
1 ======================
1
1 This section is specific for the GNU Objective-C runtime. If you are
1 using a different runtime, you can skip it.
1
1 Support for garbage collection with the GNU runtime has been added by
1 using a powerful conservative garbage collector, known as the
1 Boehm-Demers-Weiser conservative garbage collector.
1
1 To enable the support for it you have to configure the compiler using
1 an additional argument, '--enable-objc-gc'. This will build the
1 boehm-gc library, and build an additional runtime library which has
1 several enhancements to support the garbage collector. The new library
1 has a new name, 'libobjc_gc.a' to not conflict with the
1 non-garbage-collected library.
1
1 When the garbage collector is used, the objects are allocated using the
1 so-called typed memory allocation mechanism available in the
1 Boehm-Demers-Weiser collector. This mode requires precise information
1 on where pointers are located inside objects. This information is
1 computed once per class, immediately after the class has been
1 initialized.
1
1 There is a new runtime function 'class_ivar_set_gcinvisible()' which
1 can be used to declare a so-called "weak pointer" reference. Such a
1 pointer is basically hidden for the garbage collector; this can be
1 useful in certain situations, especially when you want to keep track of
1 the allocated objects, yet allow them to be collected. This kind of
1 pointers can only be members of objects, you cannot declare a global
1 pointer as a weak reference. Every type which is a pointer type can be
1 declared a weak pointer, including 'id', 'Class' and 'SEL'.
1
1 Here is an example of how to use this feature. Suppose you want to
1 implement a class whose instances hold a weak pointer reference; the
1 following class does this:
1
1
1 @interface WeakPointer : Object
1 {
1 const void* weakPointer;
1 }
1
1 - initWithPointer:(const void*)p;
1 - (const void*)weakPointer;
1 @end
1
1
1 @implementation WeakPointer
1
1 + (void)initialize
1 {
1 if (self == objc_lookUpClass ("WeakPointer"))
1 class_ivar_set_gcinvisible (self, "weakPointer", YES);
1 }
1
1 - initWithPointer:(const void*)p
1 {
1 weakPointer = p;
1 return self;
1 }
1
1 - (const void*)weakPointer
1 {
1 return weakPointer;
1 }
1
1 @end
1
1
1 Weak pointers are supported through a new type character specifier
1 represented by the '!' character. The 'class_ivar_set_gcinvisible()'
1 function adds or removes this specifier to the string type description
1 of the instance variable named as argument.
1