What is the Objective-C equivalent for "toString()", for use with NSLog?

George Armhold picture George Armhold · Jul 9, 2009 · Viewed 55.6k times · Source

Is there a method that I can override in my custom classes so that when

      NSLog(@"%@", myObject) 

is called, it will print the fields (or whatever I deem important) of my object? I guess I'm looking for the Objective-C equivalent of Java's toString().

Answer

zakovyrya picture zakovyrya · Jul 9, 2009

It is the description instance method, declared as:

- (NSString *)description

Here's an example implementation (thanks to grahamparks):

- (NSString *)description {
   return [NSString stringWithFormat: @"Photo: Name=%@ Author=%@", name, author];
}