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()
.
You can override the description method of NSObject:
On the subject of logging I recommend this blog post for better logging in Objective-C.
It is the
description
instance method, declared as:Here's an example implementation (thanks to grahamparks):
Add this to the
@implementation
of your Photo class:This will output the available voices:
There are two functions that you can use.
This will be displayed when you put your object as, I.E. a parameter for
NSLog
. The other description function is:This will be called when you do
po anInstanceOfYourClass
in the debug command window. If your class doesn't have adebugDescription
function, then justdescription
will be called.Note that the base class
NSObject
does havedescription
implemented, but it is fairly bare-bones: it only displays the address of the object. This is why I recommend that you implementdescription
in any class you want to get info out of, especially if you use thedescription
method in your code. If you do usedescription
in your code, I suggest you implementdebugDescription
as well, also makingdebugDescription
more verbose.