Search code examples
objective-ctostringnslog

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


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


Solution

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