3

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

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

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

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

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

4

3 回答 3

15

你必须使用KVC

NSDictionary *dict = @{@"key1" : @"value1", @"key2" : @"value2", @"key3" : @"value3"};
for (NSString *key in [dict allKeys]) {
   [self setValue:dict[key] forKey:key];
}
于 2012-08-24T16:29:27.630 回答
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];
于 2012-08-24T16:41:50.200 回答
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

于 2015-11-05T18:43:22.097 回答