Facing new challenges everyday

Returning a textual representation of a object in Objective-C

February 28th, 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.

DZoneGoogle BookmarksFacebookEvernoteLinkedInDeliciousShare

No Comments »

No comments yet.

Leave a comment

:mrgreen: :neutral: :twisted: :shock: :smile: :???: :cool: :evil: :grin: :oops: :razz: :roll: :wink: :cry: :eek: :lol: :mad: :sad:
*

RSS feed for these comments. | TrackBack URI

Visitors Around the World

Polls

How Is My Site?

View Results

Loading ... Loading ...

Categories

Meta

Links

hosted by easy2use.net