Did I reinvent the wheel?
Did I reinvent the wheel?
- Subject: Did I reinvent the wheel?
- From: Jeff LaMarche <email@hidden>
- Date: Fri, 18 Jul 2008 13:22:13 -0400
Hey, folks. I needed an easy way to turn dictionaries into objects and
objects into dictionaries based on their properties. I didn't want to
have to custom code this for each of the classes i was using, and I
couldn't find that functionality in any of the existing objects, but I
have this sneaking suspicion that it's in there somewhere. I'd
obviously prefer to use the delivered version if one exists.
So, here's what I'm using now - is this a case of solving a problem
that didn't need to be solved?
<code>
@implementation NSObject(ToFromDict)
-(NSDictionary *)dictionaryRepresentation {
unsigned int outCount;
NSMutableArray *properties = [NSMutableArray
arrayWithCapacity:outCount];
objc_property_t *propList = class_copyPropertyList([self class],
&outCount);
int i;
for (i=0; i < outCount; i++)
{
objc_property_t * oneProp = propList + i;
NSString *propName = [[NSString alloc]
initWithCString:property_getName(*oneProp)];
[properties addObject:propName];
[propName release];
}
return [self dictionaryWithValuesForKeys:properties];
}
-(id)initWithDictionary:(NSDictionary *)dict {
if (self=[self init])
{
[self setValuesForKeysWithDictionary:dict];
}
return self;
}
@end
</code>
Thanks.
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden