Returning a textual representation of a object in Objective-C
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 |
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.