Feeling like a moron - question about description


I see in the method for description in Employee.m how an NSString is called with the format @"< Employee %d: %d in assets >\n". And when I run the program, sure enough all of the information related to the employee prints out before I begin deallocating. But where on earth do we “call” this description method in main.m? I guess I am unsure why description gets used here before we begin deallocating. Can someone explain?

Please and thank you!


The description method is called if you NSLog an object with %@. When NSLog sees a %@ in its format string, it invokes the description method of the corresponding object in the list of the arguments passed to it.

For example:

//  main.m

#import <Foundation/Foundation.h>

@interface Foo: NSObject

int main (int argc, const char * argv[])
    @autoreleasepool {

        Foo *foo = [[Foo alloc] init];
        NSLog (@"%@", foo);
        NSLog (@"%@", [[Foo alloc] init]);
    fflush (NULL);
    return 0;

@implementation Foo

- (NSString *)description
    return [NSString stringWithFormat:@"I am a %@ and I live at %p in memory", [self className], self];

The output:

2013-01-10 16:28:38.935 Lightenbulb [1196:403] I am a Foo and I live at 0x7fa7e0c14110 in memory
2013-01-10 16:28:38.936 Lightenbulb [1196:403] I am a Foo and I live at 0x7fa7e0c022d0 in memory


Thank you!