The equivalent of ‘toString’ in Objective-C.

If you’ve ever wondered if there’s a convenient way in Objective-C to write a function for “expressing” the value of an object of yours, as a string, just like “toString” in e.g. JavaScript (and Java? I think), I’ve got good news:

-(NSString *)description

Add the above method to your Objective-C class and you’ll be able to NSLog it or get its string value anywhere using [OBNAME description]. In short, it will now respond with its ‘description’ to ‘%@’ in an NSString stringWithFormat expression.

Example:

@interface Person : NSObject {
  NSString *name;
  NSString *phone;
  NSInteger age;
}

-(NSString *)description;
[...]
-(NSString *)description
{
  return [NSString stringWithFormat:@"%@ (%d): %@",
        name, age, phone];
}

Then somewhere we have a Person object and we want to see its value.

NSLog(@"We've got %@", aPerson);
myLabel.text = [NSString stringWithFormat:@"Details: %@", aPerson];

(pardon any errors in code above — untested as is)

This entry was posted in Software and tagged , , , , , , , , . Bookmark the permalink.

2 Responses to The equivalent of ‘toString’ in Objective-C.

  1. Chris Hanson says:

    Actually, ‘toString’ is the Java equivalent of the -description method. (Java was derived in part from Objecive-C.)

  2. Kalle says:

    Huh! Didn’t know that! :O

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">