Skip to content

Instantly share code, notes, and snippets.

@HeshamMegid
Last active July 10, 2019 13:11
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save HeshamMegid/4654512 to your computer and use it in GitHub Desktop.
Save HeshamMegid/4654512 to your computer and use it in GitHub Desktop.
#import <Foundation/Foundation.h>
@interface NSObject (NSDictionaryRepresentation)
/**
Returns an NSDictionary containing the properties of an object that are not nil.
*/
- (NSDictionary *)dictionaryRepresentation;
@end
#import "NSObject+NSDictionaryRepresentation.h"
#import <objc/runtime.h>
@implementation NSObject (NSDictionaryRepresentation)
- (NSDictionary *)dictionaryRepresentation {
unsigned int count = 0;
// Get a list of all properties in the class.
objc_property_t *properties = class_copyPropertyList([self class], &count);
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] initWithCapacity:count];
for (int i = 0; i < count; i++) {
NSString *key = [NSString stringWithUTF8String:property_getName(properties[i])];
NSString *value = [self valueForKey:key];
// Only add to the NSDictionary if it's not nil.
if (value)
[dictionary setObject:value forKey:key];
}
free(properties);
return dictionary;
}
@end
@hamdshah
Copy link

nice man... But dictionary is not released :)

@HeshamMegid
Copy link
Author

@hamdullahshah That's being used in an ARC project.

@hamdshah
Copy link

Oops sorry my mistake :)

@specpropeller
Copy link

pretty cool .. thanx
Would it make sense to add to NSObject something like setValuesFromRepresentation (KVC)? Or would it be against rules to put that feature into something like + initWithRepresentation?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment