Re: Did I reinvent the wheel?
Re: Did I reinvent the wheel?
- Subject: Re: Did I reinvent the wheel?
- From: Jean-Daniel Dupas <email@hidden>
- Date: Fri, 18 Jul 2008 19:46:42 +0200
I don't think there is built-in support for this specific feature. If
archiving, serialization and CoreData do not fit your needs, I bet you
have to use your own method.
That said, you should avoid to use an uninitialized variable in your
code ;-) (outCount is used in array initializer before you get
property count).
Le 18 juil. 08 à 19:22, Jeff LaMarche a écrit :
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
_______________________________________________
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