iOS and Web Development on Mac OS X
Overriding Objective-C description
It is good practice to to always override the description method which is part of the NSObject protocol. Compared to other language it is equivalent to:
- C# has ToString()
- Java has to toString()
This description method will return a string representation of the object it is send to. Overriding this method can make debugging a trivial task.
Lets look at an example for a class Person which has 3 properties:
- NSString *firstName
- NSString *lastName
- NSInteger age
Inside the .m implementation file of this class Person we only need to give an implementation to description:
-(NSString *) description {
return [NSString stringWithFormat:@"Person: %@ %@ - %d", self.firstName,
self.lastName,
self.age];
}
Now it is very easy to log this description inside the console by calling:
NSLog(@"%@", person);
And the output will look like:
2011-12-14 20:23:53.508 Description Example [2705:b303] Person: John Doe - 41
It is even possible to directly call the description method inside the GDB console by using po:
(gdb) po person Person: John Doe - 41 (gdb)
Happy bug hunting!
| Print article | This entry was posted by Luc Wollants on December 14, 2011 at 19:33, and is filed under iOS, iPad, iPhone, Obj-C, Objective-C, Xcode. Follow any responses to this post through RSS 2.0. You can skip to the end and leave a response. Pinging is currently not allowed. |
about 5 months ago
Cool thanks for the hint.. i was always wondering how I can achieve that!