In Objective-C, it’s common to override -description with a method that prints the object ID and instance variable names/values. I’d like to make a generic -description method that does this through introspection, rather than manually doing this for each class. I’d like the output to be something like:
<ClassName: 0x??????, ivar1: value1, ivar2: value2, ivar3: value3, ...>
It would also be nice to sort by instance variable name (so they are always in the same order). Finally, if this could be put into a category safely overriding the NSObject functionality, that would be perfect (but I see that’s not straightforward, as NSObject.m has a warning about using -[NSString stringWithFormat:] in -description).
This is a great question! Because I haven’t found anything like this, I wrote a small function that does this for you. It replaces
- (NSString *)descriptionofNSObjectusing method swizzling (yes, I’m this evil. MAHAHAHAHAHahahahaha) and prints the ivar in the order they also appear in the class (you can edit it easily to display them in alphabetical order).DON’T! forget to call
NSObjectSwizzleDescription()!.h file:
.m file: