4

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

emdog4
  • 1,975
  • 3
  • 20
  • 25

3 Answers3

17

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];
}
DrummerB
  • 39,814
  • 12
  • 105
  • 142
1

In addition to DrummerB answer, if you have nested object like below,

@interface InnerObject : NSObject
{
    NSString *innerKey1;
}
@interface MyObject : NSObject
{
    NSString *key1;
    NSString *key2;
    NSString *key3;
    InnerObject *innerObj; 
}

You can set value to the iVar innerKey1 also by below method:

MyObject *obj = [[MyObject alloc]init];
obj.innerObj = [[InnerObject alloc]init];
[obj setValue:yourValue forKeyPath:innerObj.innerKey1];
Apurv
  • 17,116
  • 8
  • 51
  • 67
1

You can also initialize your instance variables/properties from a dictionary like this:

[self setValuesForKeysWithDictionary:dictionary];

Here is the official Apple Documentation on setValuesForKeysWithDictionary:

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Protocols/NSKeyValueCoding_Protocol/#//apple_ref/occ/instm/NSObject/setValuesForKeysWithDictionary:

Scott Marchant
  • 3,447
  • 2
  • 22
  • 29