Any object can implement the description method that is used to return a description of the contents of a receiver. The problem i have always found with this method. Is keeping the method up to date during the development process. Also getting other developers working on the project also keeping it up to date.
With that problem in mind I put together this method that will automatically generate the string and list all available properties in the the receiver. It will print out when the instance is used in NSLog or or printed using the GDB debugger commands in my previous post.
[objc]
#import <objc/runtime.h>
//this will automatically create a description
//based on the properties
– (NSString*) description
{
unsigned int propCount, i;
//gets a list of all properties in the
//created in this class and the property count
objc_property_t *properties = class_copyPropertyList([self class], &propCount);
//used to hold all the properties
NSMutableArray *keys = [NSMutableArray arrayWithCapacity:propCount];
for(i = 0; i < propCount; i++)
{
//extracts a single property
objc_property_t property = properties[i];
//gets the property name
const char *propName = property_getName(property);
//checks to make sure there is a name
if(propName)
{
//converts the name to a usable object
NSString *propertyName = [NSString stringWithCString:propName
encoding:NSNonLossyASCIIStringEncoding];
//adds it to a list of keys
[keys addObject:propertyName];
}
}
//frees the properties
free(properties);
//attempt to simulate the dictionary log by using the %p to get the memory address
//the last %@ is used for all the items added to the dictionary
return [NSString stringWithFormat:@"<%@: %p; %@>",
NSStringFromClass([self class]),
self,
[self dictionaryWithValuesForKeys:keys]];
}
[/objc]
You can also find it on my custom xCode 4 templates here on github. Right at the bottom the class.