## 3 Working with Objects

Objective-C and GNUstep provide a rich object allocation and memory management framework. Objective-C affords independent memory allocation and initialization steps for objects, and GNUstep supports three alternative schemes for memory management.

### 3.1 Initializing and Allocating Objects

Unlike most object-oriented languages, Objective-C exposes memory allocation for objects and initialization as two separate steps. In particular, every class provides an ’`+alloc`’ method for creating blank new instances. However, initialization is carried out by an instance method, not a class method. By convention, the default initialization method is ’`-init`’. The general procedure for obtaining a newly initialized object is thus:

    id newObj = [[SomeClass alloc] init];

Here, the call to `alloc` returns an uninitialized instance, on which `init` is then invoked. (Actually, `alloc` does set all instance variable memory to 0, and it initializes the special `isa` variable mentioned earlier which points to the object’s class, allowing it to respond to messages.) The `alloc` and `init` calls may be collapsed for convenience into a single call:

    id newObj = [SomeClass new];

The default implementation of `new` simply calls `alloc` and `init` as above, however other actions are possible. For example, `new` could be overridden to reuse an existing object and just call `init` on it (skipping the `alloc` step). (Technically this kind of instantiation management can be done inside `init` as well – it can deallocate the receiving object and return another one in its place. However this practice is not recommended; the `new` method should be used for this instead since it avoids unnecessary memory allocation for instances that are not used.)

#### 3.1.1 Initialization with Arguments

In many cases you want to initialize an object with some specific information. For example a `Point` object might need to be given an x, y position. In this case the class may define additional initializers, such as:

    id pt = [[Point alloc] initWithX: 1.5 Y: 2.0];

Again, a `new` method may be defined, though sometimes the word “new” is not used in the name:

    id pt = [Point newWithX: 1.5 Y: 2.0];
      // alternative
    id pt = [Point pointAtX: 1.5 Y: 2.0];

In general the convention in Objective-C is to name initializers in a way that is intuitive for their classes. Initialization is covered in more detail in Instance Initialization. Finally, it is acceptable for an `init...` method to return `nil` at times when insufficient memory is available or it is passed an invalid argument; for example the argument to the `NSString` method `initWithContentsOfFile:` may be an erroneous file name.

#### 3.1.2 Memory Allocation and Zones

Memory allocation for objects in GNUstep supports the ability to specify that memory is to be taken from a particular region of addressable memory. In the days that computer RAM was relatively limited, it was important to be able to ensure that parts of a large application that needed to interact with one another could be held in working memory at the same time, rather than swapping back and forth from disk. This could be done by specifying that particular objects were to be allocated from a particular region of memory, rather than scattered across all of memory at the whim of the operating system. The OS would then keep these objects in memory at one time, and swap them out at the same time, perhaps to make way for a separate portion of the application that operated mostly independently. (Think of a word processor that keeps structures for postscript generation for printing separate from those for managing widgets in the onscreen editor.)

With the growth of computer RAM and the increasing sophistication of memory management by operating systems, it is not as important these days to control the regions where memory is allocated from, however it may be of use in certain situations. For example, you may wish to save time by allocating memory in large chunks, then cutting off pieces yourself for object allocation. If you know you are going to be allocating large numbers of objects of a certain size, it may pay to create a zone that allocates memory in multiples of this size. The GNUstep/Objective-C mechanisms supporting memory allocation are therefore described here.

The fundamental structure describing a region of memory in GNUstep is called a Zone, and it is represented by the `NSZone` struct. All `NSObject` methods dealing with the allocation of memory optionally take an `NSZone` argument specifying the Zone to get the memory from. For example, in addition to the fundamental `alloc` method described above, there is the `allocWithZone:` method:

    + (id) alloc;
    + (id) allocWithZone: (NSZone*)zone;

Both methods will allocate memory to hold an object, however the first one automatically takes the memory from a default Zone (which is returned by the `NSDefaultMallocZone()` function). When it is necessary to group objects in the same area of memory, or allocate in chunks - perhaps for performance reasons, you may create a Zone from where you would allocate those objects by using the `NSCreateZone` function. This will minimise the paging required by your application when accessing those objects frequently. In all normal yuse however, you should confine yourself to the default zone.

Low level memory allocation is performed by the `NSAllocateObject()` function. This is rarely used but available when you require more advanced control or performance. This function is called by `[NSObject +allocWithZone:]`. However, if you call `NSAllocateObject()` directly to create an instance of a class you did not write, you may break some functionality of that class, such as caching of frequently used objects.

Other `NSObject` methods besides `alloc` that may optionally take Zones include `-copy` and `-mutableCopy`. For 95% of cases you will probably not need to worry about Zones at all; unless performance is critical, you can just use the methods without zone arguments, that take the default zone.

#### 3.1.3 Memory Deallocation

Objects should be deallocated from memory when they are no longer needed. While there are several alternative schemes for managing this process (see next section), they all eventually resort to calling the `NSObject` method `-dealloc`, which is more or less the opposite of `-alloc`. It returns the memory occupied by the object to the Zone from which it was originally allocated. The `NSObject` implementation of the method deallocates only instance variables. Additional allocated, unshared memory used by the object must be deallocated separately. Other entities that depend solely on the deallocated receiver, including complete objects, must also be deallocated separately. Usually this is done by subclasses overriding `-dealloc` (see Instance Deallocation).

As with `alloc`, the underlying implementation utilizes a function (`NSDeallocateObject()`) that can be used by your code if you know what you are doing.

### 3.2 Memory Management

In an object-oriented environment, ensuring that all memory is freed when it is no longer needed can be a challenge. To assist in this regard, there are three alternative forms of memory management available in Objective-C:

- - Explicit
  You allocate objects using `alloc`, `copy` etc, and deallocate them when you have finished with them (using `dealloc`). This gives you complete control over memory management, and is highly efficient, but error prone.
- - Retain count
  You use the OpenStep retain/release mechanism, along with autorelease pools which provide a degree of automated memory management. This gives a good degree of control over memory management, but requires some care in following simple rules. It’s pretty efficient.
- - Garbage collection
  You build the GNUstep base library with garbage collection, and link with the Boehm GC library … then never bother about releasing/deallocating memory. This requires a slightly different approach to programming … you need to take care about what happens when objects are deallocated … but don’t need to worry about deallocating them.

The recommended approach is to use some standard macros defined in `NSObject.h` which encapsulate the retain/release/autorelease mechanism, but which permit efficient use of the garbage collection system if you build your software with that. We will justify this recommendation after describing the three alternatives in greater detail.

#### 3.2.1 Explicit Memory Management

This is the standard route to memory management taken in C and C++ programs. As in standard C when using `malloc`, or in C++ when using `new` and `delete`, you need to keep track of every object created through an `alloc` call and destroy it by use of `dealloc` when it is no longer needed. You must make sure to no longer reference deallocated objects; although messaging them will not cause a segmentation fault as in C/C++, it will still lead to your program behaving in unintended ways.

This approach is generally not recommended since the Retain/Release style of memory management is significantly less leak-prone while still being quite efficient.

#### 3.2.2 OpenStep-Style (Retain/Release) Memory Management

The standard OpenStep system of memory management employs retain counts. When an object is created, it has a retain count of 1. When an object is retained, the retain count is incremented. When it is released the retain count is decremented, and when the retain count goes to zero the object gets deallocated.

      Coin	*c = [[Coin alloc] initWithValue: 10];

        // Put coin in pouch,
      [c retain];	// Calls 'retain' method (retain count now 2)
        // Remove coin from pouch
      [c release];	// Calls 'release' method (retain count now 1)
        // Drop in bottomless well
      [c release];	// Calls 'release' ... (retain count 0) then 'dealloc'

One way of thinking about the initial retain count of 1 on the object is that a call to `alloc` (or `copy`) implicitly calls `retain` as well. There are a couple of default conventions about how `retain` and `release` are to be used in practice.

- If a block of code causes an object to be allocated, it “owns” this object and is responsible for releasing it. If a block of code merely receives a created object from elsewhere, it is not responsible for releasing it.
- More generally, the total number of `retain`s in a block should be matched by an equal number of `release`s.

Thus, a typical usage pattern is:

      NSString *msg = [[NSString alloc] initWithString: @"Test message."];
      NSLog(msg);
        // we created msg with alloc -- release it
      [msg release];

Retain and release must also be used for instance variables that are objects:

    - (void)setFoo:(FooClass *newFoo)
    {
        // first, assert reference to newFoo
      [newFoo retain];
        // now release reference to foo (do second since maybe newFoo == foo)
      [foo release];
        // finally make the new assignment; old foo was released and may
        // be destroyed if retain count has reached 0
      foo = newFoo;
    }

Because of this retain/release management, it is safest to use accessor methods to set variables even within a class:

    - (void)resetFoo
    {
      FooClass *foo = [[FooClass alloc] init];
      [self setFoo: foo];
        // since -setFoo just retained, we can and should
        // undo the retain done by alloc
      [foo release];
    }

Exceptions

In practice, the extra method call overhead should be avoided in performance critical areas and the instance variable should be set directly. However in all other cases it has proven less error-prone in practice to consistently use the accessor.

There are certain situations in which the rule of having retains and releases be equal in a block should be violated. For example, the standard implementation of a container class `retain`s each object that is added to it, and `release`s it when it is removed, in a separate method. In general you need to be careful in these cases that retains and releases match.

#### 3.2.2.1 Autorelease Pools

One important case where the retain/release system has difficulties is when an object needs to be transferred or handed off to another. You don’t want to retain the transferred object in the transferring code, but neither do you want the object to be destroyed before the handoff can take place. The OpenStep/GNUstep solution to this is the autorelease pool. An autorelease pool is a special mechanism that will retain objects it is given for a limited time – always enough for a transfer to take place. This mechanism is accessed by calling `autorelease` on an object instead of `release`. `Autorelease` first adds the object to the active autorelease pool, which retains it, then sends a `release` to the object. At some point later on, the pool will send the object a second `release` message, but by this time the object will presumably either have been retained by some other code, or is no longer needed and can thus be deallocated. For example:

    - (NSString *) getStatus
    {
      NSString *status =
        [[NSString alloc] initWithFormat: "Count is %d", [self getCount]];
       // set to be released sometime in the future
      [status autorelease];
      return status;
    }

Any block of code that calls `-getStatus` can also forego retaining the return value if it just needs to use it locally. If the return value is to be stored and used later on however, it should be retained:

      ...
      NSString *status = [foo getStatus];
        // 'status' is still being retained by the autorelease pool
      NSLog(status);
      return;
        // status will be released automatically later

      ...
      currentStatus = [foo getStatus];
        // currentStatus is an instance variable; we do not want its value
        // to be destroyed when the autorelease pool cleans up, so we
        // retain it ourselves
      [currentStatus retain];

Convenience Constructors

A special case of object transfer occurs when a convenience constructor is called (instead of `alloc` followed by `init`) to create an object. (Convenience constructors are class methods that create a new instance and do not start with “new”.) In this case, since the convenience method is the one calling `alloc`, it is responsible for releasing it, and it does so by calling `autorelease` before returning. Thus, if you receive an object created by any convenience method, it is autoreleased, so you don’t need to release it if you are just using it temporarily, and you DO need to retain it if you want to hold onto it for a while.

    - (NSString *) getStatus
    {
        NSString *status =
            [NSString stringWithFormat: "Count is %d", [self getCount]];
        // 'status' has been autoreleased already
        return status;
    }

Pool Management

An autorelease pool is created automatically if you are using the GNUstep GUI classes, however if you are just using the GNUstep Base classes for a nongraphical application, you must create and release autorelease pools yourself:

      NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

Once a pool has been created, any autorelease calls will automatically find it. To close out a pool, releasing all of its objects, simply release the pool itself:

      [pool release];

To achieve finer control over autorelease behavior you may also create additional pools and release them in a nested manner. Calls to `autorelease` will always use the most recently created pool.

Finally, note that `autorelease` calls are significantly slower than plain `release`. Therefore you should only use them when they are necessary.

#### 3.2.2.2 Avoiding Retain Cycles

One difficulty that sometimes occurs with the retain/release system is that cycles can arise in which, essentially, Object A has retained Object B, and Object B has also retained Object A. In this situation, neither A nor B will ever be deallocated, even if they become completely disconnected from the rest of the program. In practice this type of situation may involve more than two objects and multiple retain links. The only way to avoid such cycles is to be careful with your designs. If you notice a situation where a retain cycle could arise, remove at least one of the links in the chain, but not in such a way that references to deallocated objects might be mistakenly used.

#### 3.2.2.3 Summary

The following summarizes the retain/release-related methods:

Method | Description
`-retain` | increases the reference count of an object by 1
`-release` | decreases the reference count of an object by 1
`-autorelease` | decreases the reference count of an object by 1 at some stage in the future
`+alloc` and `+allocWithZone:` | allocates memory for an object, and returns it with retain count of 1
`-copy`, `-mutableCopy`, `copyWithZone:` and `-mutableCopyWithZone:` | makes a copy of an object, and returns it with retain count of 1
`-init` and any method whose name begins with `init` | initialises the receiver, returning the retain count unchanged. `-init` has had no effect on the reference count.
`-new` and any method whose name begins with `new` | allocates memory for an object, initialises it, and returns the result.
`-dealloc` | deallocates object immediately (regardless of value of retain count)
convenience constructors | allocate memory for an object, and returns it in an autoreleased state (retain=1, but will be released automatically at some stage in the future). These constructors are class methods whose name generally begins with the name of the class (initial letter converted to lowercase).

The following are the main conventions you need to remember:

- If a unit of code allocates, retains, or copies an object, the same unit, loosely speaking, is responsible for releasing or autoreleasing it at some future point. It is best to balance retains and releases within each individual block of code.
- If you receive an object, it should remain valid until the object which provided it is sent another message or until the autorelease pool which was in use at the point when you received it is emptied. So you can usually expect it to remain valid for the rest of the current method call and can even return it as the result of the method. If you need to store it away for future use (e.g. as an instance variable, or to use after emptying/destroying an autorelease pool, or to be used after sending another message to the object’s owner), you must retain it.
- The retain counts mentioned are guidelines only ... more sophisticated classes often perform caching and other tricks, so that `+alloc` methods may retain an instance from a cache and return it, and `-init` methods may release their receiver and return a different object (possibly obtained by retaining a cached object). In these cases, the retain counts of the returned objects will obviously differ from the simple examples, but the ownership rules (how you should use the returned values) remain the same.

#### 3.2.3 Garbage Collection Based Memory Management

The GNUstep system can be optionally compiled with a memory sweeping garbage collection mechanism using the Boehm conservative garbage collection library (http://www.hpl.hp.com/personal/Hans_Boehm/gc). In this case, you need not worry about retaining and releasing objects; the garbage collector will automatically track which objects are still referred to at any given point within the program, and which are not. Those that are not are automatically deallocated. The situation is largely similar to programming in Java, except that garbage collection will only be triggered during memory allocation requests and will be less efficient since pointers in C are not always explicitly marked.

Whether in Java or Objective-C, life is still not completely worry-free under garbage collection however. You still must “help the garbage collector along” by explicitly dropping references to objects when they become unneeded. Failing to do this is easier than you might think, and leads to memory leaks.

When GNUstep was compiled with garbage collection, the macro flag `GS_WITH_GC` will be defined, which you can use in programs to determine whether you need to call `retain`, `release`, etc.. Rather than doing this manually, however, you may use special macros in place of the `retain` and `release` method calls. These macros call the methods in question when garbage collection is not available, but do nothing when it is.

Macro | Functionality
`RETAIN(foo);` | `[foo retain];`
`RELEASE(foo);` | `[foo release];`
`AUTORELEASE(foo);` | `[foo autorelease];`
`ASSIGN(foo, bar);` | `[bar retain]; [foo release]; foo = bar;`
`ASSIGNCOPY(foo, bar);` | `[foo release]; foo = [bar copy];`
`DESTROY(foo);` | `[foo release]; foo = nil;`

In the latter three “convenience” macros, appropriate `nil` checks are made so that no retain/release messages are sent to `nil`.

Some authorities recommend that you always use the RETAIN/RELEASE macros in place of the actual method calls, in order to allow running in a non-garbage collecting GNUstep environment yet also save unneeded method calls in the case your code runs in a garbage collecting enviromnent. On the other hand, if you know you are always going to be running in a non-garbage collecting environment, there is no harm in using the method calls, and if you know you will always have garbage collection available you can save development effort by avoiding any use of retain/release or RETAIN/RELEASE.

#### 3.2.4 Current Recommendations

As of May 2004 the garbage collection in GNUstep was still considered beta quality (some bugs exist). In the OS X world, Apple’s Cocoa does not employ garbage collection, and it is not clear whether there are plans to implement it. Therefore the majority of GNUstep programmers use the RETAIN/RELEASE approach to memory management.