views:

3367

answers:

3

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

+7  A: 

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.

teabot
Isn't this a static method? I'd like this to operate on objects rather than the class. For example, if I have a "Photo" class, with fields "name" and "author", I'd like NSLog to print those fields as they are assigned in the object.
Caffeine Coma
Yes - well spotted - I pressed the wrong key. I clearly should pay more attention when proof reading my answers. Thankfully someone had their eye on the ball :-)
teabot
+11  A: 

Actually, it's

- (NSString *)description

It's instance method, not class

zakovyrya
+2  A: 

Add this to the @implementation of your Photo class:

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