Returning a textual representation of a object in Objective-C

Posted by – February 28, 2009

Today I discovered how objetive-c allows the programmer to generate a textual representation of a object, you can do it by implementing a description method of NSObject protocol.

Please consider the following class interface:

Contact.h

1
2
3
4
5
6
7
8
9
@interface Contact : NSObject {
    NSString *name;
    NSString *address;
}

@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSString *address;

@end


And the following class implementation:

Contact.m

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#import "Contact.h"

@implementation Contact

@synthesize name;
@synthesize address;

- (NSString*) description {
    return name;
}

- (void)dealloc {
    [name release];
    [address release];

    [super dealloc];
}
@end

You can get the textual representation of a object by executing the following code:

1
2
3
4
Contact *contact = [[Contact alloc] init];
contact.name = @"Roger";

NSLog([contact description]);

This will generate the following output:

Roger

Simple, isn’t? Exactly like Object.toString() of Java does.

Share

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>