Initialize instance variables as key/value pair from NSDictionary?

initialization, kvc, nsdictionary, nsobject, objective-c

Solution

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];
}

Problem

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"?

Original source