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

Viewed 57625

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().

6 Answers

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];
}

Add this to the @implementation of your Photo class:

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

You can override the description method of NSObject:

- (NSString *)description

On the subject of logging I recommend this blog post for better logging in Objective-C.

Related