Last active
July 10, 2019 13:11
-
-
Save HeshamMegid/4654512 to your computer and use it in GitHub Desktop.
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 (NSDictionaryRepresentation) | |
/** | |
Returns an NSDictionary containing the properties of an object that are not nil. | |
*/ | |
- (NSDictionary *)dictionaryRepresentation; | |
@end |
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 "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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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?