Instantiating Custom Class from NSDictionary

CIFilter picture CIFilter · May 6, 2009 · Viewed 10.1k times · Source

I have a feeling that this is stupid question, but I'll ask anyway...

I have a collection of NSDictionary objects whose key/value pairs correspond to a custom class I've created, call it MyClass. Is there an easy or "best practice" method for me to basically do something like MyClass * instance = [map NSDictionary properties to MyClass ];? I have a feeling I need to do something with NSCoding or NSKeyedUnarchiver, but rather than stumble through it on my own, I figure someone out there might be able to point me in the right direction.

Answer

retainCount picture retainCount · May 6, 2009

The -setValuesForKeysWithDictionary: method, along with -dictionaryWithValuesForKeys:, is what you want to use.

Example:

// In your custom class
+ (id)customClassWithProperties:(NSDictionary *)properties {
   return [[[self alloc] initWithProperties:properties] autorelease];
}

- (id)initWithProperties:(NSDictionary *)properties {
   if (self = [self init]) {
      [self setValuesForKeysWithDictionary:properties];
   }
   return self;
}

// ...and to easily derive the dictionary
NSDictionary *properties = [anObject dictionaryWithValuesForKeys:[anObject allKeys]];