Created
April 10, 2012 22:01
-
-
Save justin/2354923 to your computer and use it in GitHub Desktop.
NSObject+FancyDescription
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation/Foundation.h> | |
@interface NSObject (FancyDescription) | |
// | |
// Output the values of all the properties associated with a given class. | |
// Iterates all the way down the chain until we hit NSObject. | |
// | |
- (NSString *)sg_description; | |
@end | |
#import <objc/runtime.h> | |
#import "NSObject+FancyDescription.h" | |
@implementation NSObject (FancyDescription) | |
- (NSString *)fancyDescriptionForClassType:(Class)classType | |
{ | |
NSMutableString *description = [NSMutableString string]; | |
Class superClass = class_getSuperclass(classType); | |
if ((superClass != nil) && ([superClass isSubclassOfClass:[NSObject class]] == NO)) | |
{ | |
[description appendString:[self fancyDescriptionForClassType:superClass]]; | |
} | |
NSUInteger numberOfProperties = 0; | |
objc_property_t *propertyList = class_copyPropertyList(classType, &numberOfProperties); | |
NSInteger i; | |
for (i = 0 ; i < numberOfProperties ; i++) | |
{ | |
objc_property_t property = propertyList[i]; | |
const char *property_name = property_getName(property); | |
NSString *propertyName = [NSString stringWithCString:property_name encoding:NSASCIIStringEncoding]; | |
if (propertyName != nil) | |
{ | |
id value = [self valueForKey:propertyName]; | |
[description appendFormat:@"\n%@ = %@\n", propertyName, value]; | |
} | |
} | |
free(propertyList); | |
return description; | |
} | |
#pragma mark - | |
#pragma mark Instance Methods | |
// +-------------------------------------------------------------------- | |
// | Instance Methods | |
// +-------------------------------------------------------------------- | |
- (NSString *)sg_description | |
{ | |
return [NSString stringWithFormat:@"%@: {%@}", NSStringFromClass([self class]), [self fancyDescriptionForClassType:[self class]]]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment