Skip to content

Instantly share code, notes, and snippets.

@lamprosg
Created August 22, 2014 14:14
Show Gist options
  • Select an option

  • Save lamprosg/409f0a0bf88c0ee88abb to your computer and use it in GitHub Desktop.

Select an option

Save lamprosg/409f0a0bf88c0ee88abb to your computer and use it in GitHub Desktop.
(iOS) Object to NSDictionary conversion
#import <objc/runtime.h>
ProductDetails *details = [[ProductDetails alloc] init];
details.name = @"Soap1";
details.color = @"Red";
details.quantity = 4;
NSDictionary *dict = [NSDictionary dictionaryWithPropertiesOfObject: details];
NSLog(@"%@", dict);
//Add this utility method in your class.
- (NSDictionary *) dictionaryWithPropertiesOfObject:(id)obj
{
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
unsigned count;
objc_property_t *properties = class_copyPropertyList([obj class], &count);
for (int i = 0; i < count; i++) {
NSString *key = [NSString stringWithUTF8String:property_getName(properties[i])];
[dict setObject:[obj valueForKey:key] forKey:key];
}
free(properties);
return [NSDictionary dictionaryWithDictionary:dict];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment