将实例变量初始化为NSDictionary的键/值对?

时间:2012-08-24 16:26:16

标签: objective-c initialization nsdictionary nsobject kvc

我将我的NSObject子类的公共接口定义为

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

是否有实现initWithDict:方法的技巧,以便我可以传递定义为

的NSDictionary
  

{“key1”:“value1”,“key2”:“value2”,“key3”:“value3”}

并且init方法可以设置相关的实例变量及其对应的“值”?

3 个答案:

答案 0 :(得分:15)

您必须使用KVC

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

答案 1 :(得分:1)

除了DrummerB的回答,如果您有如下的嵌套对象,

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

您也可以通过以下方法将值设置为iVar innerKey1:

MyObject *obj = [[MyObject alloc]init];
obj.innerObj = [[InnerObject alloc]init];
[obj setValue:yourValue forKeyPath:innerObj.innerKey1];

答案 2 :(得分:1)

您还可以从字典中初始化实例变量/属性,如下所示:

[self setValuesForKeysWithDictionary:dictionary];

以下是有关setValuesForKeysWithDictionary的官方Apple文档:

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