11.4 Allocating and de-allocating Instances

The syntax diagram of Objective-C classes shows that the notion of constructor and destructor is not supported in Objective-C. New instances are created in a 2-step process:

  1. Call the ’alloc’ method (send an ’alloc’ message): This is a class method of NSObject, and returns a pointer to memory for the new instance. The use of alloc is a convention in Objective-C.
  2. Send an ’initXXX’ message. By convention, all classes have one or more ’InitXXX’ methods that initializes all fields in the instance. This method will return the final instance pointer, which may be Nil.

The following code demonstrates this:

  obj: NSObject;  
  // First allocate the memory.  
  // Next, initialise.  
  // Always check the result !!  
  if (Obj=Nil) then  
    // Some error;

By convention, the initXXX method will return Nil if initialization of some fields failed, so it is imperative that the result of the function is tested.

Similarly, no privileged destructor exists; By convention, the dealloc method fullfills the cleanup of the instances. This method can be overridden to perform any cleanup necessary. Like Destroy, it should never be called directly, instead, the release method should be called instead: All instances in Objective-C are reference counted, and release will only call dealloc if the reference count reaches zero.