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


The NSZone class and memory allocation

Object allocation is performed from zones that group related objects in a zone of memory. A zone is represented in libFoundation by an instance of a subclass of NSZone. A zone is an object that not only keeps the memory zone from which the objects are allocated, but also encapsulates the algorithms that manage the memory allocation from that zone.

Traditionally, NSZone is implemented as a structure. In libFoundation, NSZone is a class instead of a struct, and the related zone functions are static inline functions that invoke the corresponding methods of the zone instance. The idea behind the definition of the NSZone as a class and not as a struct is to offer the user of the library the possibility to build his own allocator and to let current and future allocators coexist.

Currently three zones are available: NSDefaultZone, NSAllocDebugZone and StackZone. The first two they can be used only through the NSZone class and not directly. When libFoundation is compiled with support for the Boehm's garbage collector the allocation is done using only the collector's allocation functions and the entire mechanism described below for the NSZone classes is completely unused.

When the program first starts a default zone is created automatically. This zone is either an instance of the NSDefaultZone or of the NSAllocDebugZone class, depending on the mode in which the program is run. If the program runs using the reference counting mechanism, the environment variable ALLOCDEBUG is checked. If the variable exists in your environment then the default zone will be an instance of NSAllocDebugZone. If this environment variable is not defined then an instance of NSDefaultZone becomes the default zone. If the program runs using the Boehm's garbage collector, no zones are used; for more information see section Zones and garbage collection.

You can change the default zone from which the future objects will be allocated using the setDefaultZone: method. To do this you have to create an instance of the zone you want to allocate objects from and call the +setDefaultZone: method of NSZone with the new instance. The zones are kept into a stack, the most recent zone being passed to setDefaultZone: being the top of the stack. When you release a zone and it has to be deallocated, the zone is removed from the stack of zones. If the zone object happens to be the top of the stack, the zone under it becomes the new default zone.


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