简体   繁体   English

如何在 Objective-C 中添加 NSDictionary 作为值?

[英]How to add NSDictionary as a value in Objective-C?

I have a property:我有一个财产:

@property (nonatomic, strong) NSMutableDictionary<NSString *, NSMutableDictionary<NSString *, NSString *>*>*mainDict;

So it is a dictionary with another dictionary as its value.所以它是一个字典,另一个字典作为它的值。 Now, when I wanna populate my dictionary, I do:现在,当我想填充我的字典时,我会:

NSData *data = [json_string dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

for (NSString *key in [[json objectForKey:@"countries"] allKeys]) {
    NSDictionary *innerDictionary = [json objectForKey:@"countries"][key];
    [mainDict setObject:innerDictionary forKey:key];
}

when I debug, I see that my innerDictionary is correct and has its values but somehow my mainDict is not being filled.当我调试时,我看到我的innerDictionary是正确的并且有它的值,但不知何故我的 mainDict 没有被填充。

Could you please tell me what I do wrong?你能告诉我我做错了什么吗?

Declaring mainDict as a @property will create an instance variable in your class, but that variable will be nil.将 mainDict 声明为 @property 将在 class 中创建一个实例变量,但该变量将为 nil。

You'll need to initialize the mainDict somewhere before your population code gets called, perhaps in your -init, -viewDidLoad, or somewhere appropriate for your app's architecture.您需要在调用填充代码之前在某个地方初始化 mainDict,可能在您的 -init、-viewDidLoad 或适合您应用程序架构的某个地方。

mainDict initialization should look like: mainDict 初始化应如下所示:

mainDict = [[NSMutableDictionary alloc] init];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM