tags:

views:

398

answers:

2

I have a class and I want to setup what is printed when I call NSLog with that class. For example,

NSLog(@"%@",nonstandardObject);

How do I setup the object so it prints out what I'd want?

+7  A: 

Override the -description method. It takes no parameters and returns an NSString that get's printf'd out.

There's another variant called -debugDescription (returns NSString, no parameters) that's used when po'ing the object from gdb.

Dave DeLong
When subclassing from classes other than NSObject, it's worth considering adding a call to `[super description]` before outputting results for the subclass's iVars.
Abizern
@Abizern - only if you're planning on using the string that `super` gives you. Is there another reason you'd want super's description?
Dave DeLong
@Dave. Exactly, let super handle it's own description, and your class can handle the output for any added iVars. As I said; it's something to consider.
Abizern
A: 
@interface MyObject : NSObject
{
    int myInt;
}
@end

@implementation MyObject

- (id) init
{
    myInt = 4;
}

- (NSString *) description
{
    return [NSString stringWithFormat:@"myInt is %d", myInt];
}

@end

int main (int argc, char *argv[])
{
    MyObject *anInstance = [[MyObject alloc] init];

    NSLog (@"%@", anInstance);

    [anInstance release];

    return 0;
}
dreamlax