Initialize instance variables as key/value pair from NSDictionary?

emdog4 picture emdog4 · Aug 24, 2012 · Viewed 17.6k times · Source

I have my NSObject subclass's public interface defined as,

@interface MyObject : NSObject
{
    NSString *_key1;
    NSString *_key2;
    NSString *_key3;
}
- (id)initWithDict:(NSDictionary *)dict;
@end

Is there are trick to implement the initWithDict: method so that I can pass a NSDictionary defined as

{"key1" : "value1", "key2" : "value2", "key3" : "value3"}

and the init method can set the related instance variables with their corresponding "value"?

Answer

DrummerB picture DrummerB · Aug 24, 2012

You have to use KVC.

NSDictionary *dict = @{@"key1" : @"value1", @"key2" : @"value2", @"key3" : @"value3"};
for (NSString *key in [dict allKeys]) {
   [self setValue:dict[key] forKey:key];
}