Thursday, July 9, 2009

Objective-C 'description' like Java toString...

If you have done any programming in Java you may be aware of the method that will return a String representation of an object:

String toString() {
return "some string";
}

In Objective-C there is a similar class method on NSObject called description.

From the documentation description: "returns a string that describes the contents of the receiver."


WARNING: just because NSObject defines description does not mean the runtime will automatically recognize your override of the method UNLESS you explicitly declare it in your header (.h) file.

The header (.h) file
@interface MyObj : NSObject {
// instance variables
}
-(NSString *) description;

@end

Now the implementation (.m) file:
@implementation MyObj {
// instance variables
}
-(NSString *) description {
return @"My special override of description";
}

@end


Now you can do something like the following:

...
MyObj mo = [[MyObj alloc] init];

NSLog( @"Your object is: %@", mo );
...

Output:

Your object is: My special override of description


No comments:

Post a Comment