Overriding NSObject Description Method

No doubt NSLog is your friend, I use it frequently to print messages to the console during development. Actually, I use a variation of the NSLog that prints messages to the console sans date, time and object information, you can read about my approach here: Yet Another Debug Output (NSLog Replacement)

In this tip I’ll cover something similar as it relates to printing debug information to the console, specifically, overriding the description method of an object to provide information about instance variables.

NSObject and description method

All objects inherit from NSObject, which exposes a method named description. By default this method prints the object name and its address in memory.

For example, let’s say we have an object that looks as follows:

@interface testAppObject : NSObject
{
  NSString  *beerName;   // Homebrew name
  NSString  *beerStyle;  // Character and origin
  float     beerIBU;     // Bitterness range
  NSArray   *arrayHops;  // Types of hops
}

Somewhere in our code we initialize the object values to the following:

...
beerStyle = [[NSString alloc] initWithString:@"American Ale"];
beerName = [[NSString alloc] initWithString:@"Hoppy Times"];
beerIBU = 63.90;
arrayHops = [NSArray arrayWithObjects:@"Amarillo", @"Cascade", @"Centennial", @"Chinook", nil];
...

Now, let’s create an instance of that object and use NSLog to print the object to the console:

testAppObject *obj;
 
obj = [[testAppObject alloc] init];
 
NSLog(@"%@", obj);

When NSLog prints the value of the object, it calls the description method, however, the information is a little underwhelming. To its credit, you can call NSLog with other objects such as arrays, dictionaries, etc to see their values. However, requesting the description for an object does not provide specifics on the instance variables within the object.

Override description method

We can override the description method in NSObject to provide more specifics about a class.

If we add the following method to testAppObject class, overriding the description method in NSObject, we can print information for each instance variable, including the array:

- (NSString *)description
{
  return [NSString stringWithFormat:@"\nBeer style: %@ \nBeer name: %@\nIBUs = %3.2f
            \nCategories: %@", beerStyle, beerName, beerIBU, arrayHops];
}

The output for NSLog will now look as follows:

You may find this helpful when you need to see the value of all instance variables in one shot.

  1. Another timely tip, already put it to use! Thanks John.

  2. Great information – Thanks!

    What if I want to get the name of the object instance, any advice. or in your example, “obj”? Let’s say I have an array of objects passed to me. I know the object class, but I don’t know the name of each instance in the array, which I want to get. Thanks!!!!

Comments are closed.