Go to the first, previous, next, last section, table of contents.


Boehm's garbage collector support in libFoundation

libFoundation hides a lot of the interface with the Boehm's garbage collector by providing the same API for the memory management functions no matter what is the model used, the reference counting mechanism or the Boehm's garbage collector.

The objects are allocated by the library using the normal NSAllocateObject() function. In the case of Boehm's garbage collector a typed memory object is properly allocated.

Internally the memory allocation for things other than objects is performed using the Malloc, Calloc, Realloc and Free inline functions. There are also versions that are used to allocate atomic memory, MallocAtomic and CallocAtomic. These pseudo-functions are not exported but one can create similar functions for other libraries or applications.

If you need to know when a given object will be finalized, you just have to make the class adopt the GCFinalization protocol. This protocol defines a single method, -gcFinalize, that is invoked by the garbage collector when an object is about to finalize.

In addition to finalization, the GarbageCollector class provides a powerful mechanism that allows objects to be registered as observers of other objects finalization. Here are the specific methods:


@interface GarbageCollector (BoehmGCSupport)

+ (void)registerForFinalizationObserver:(id)observer
  selector:(SEL)selector
  object:(id)object;
+ (void)unregisterObserver:(id)observer
  forObjectFinalization:(id)object;

@end

When the observer object is registered for observing the finalization of object, the observer's method whose selector is represented by selector is automatically called when object is about to finalize.

You can manually unregister an object as the observer of an object finalization by using the +unregisterObserver:forObjectFinalization: method. If you provide nil for the object then observer will be unregistered for all the objects it has been previously registered as observer.

If an object registered as observer of another objects finalizes, the GarbageCollector class automatically unregisters the observer for all the objects it was observer. You don't have to take any special actions to remove the observer except if it's kept in the internal structures of your program. In this case you should register another object as an observer of the original's observer finalization and remove it from your structures. As you can see an object can be simultaneously both an observed and an observer object, there's no restriction in doing this.


Go to the first, previous, next, last section, table of contents.