如何组合两个NSDictionaries?

时间:2015-06-24 20:14:59

标签: ios objective-c nsdictionary

我正在尝试将2个NSDictionary个对象合并为1个NSMutableDictionaryNSDictionary是通过阅读2个不同的plist文件创建的。

    @property (nonatomic, strong) NSMutableDictionary *configuration;
    ...
    -(NSMutableDictionary*) configuration{
    if (!_configuration) {
      NSDictionary *core_config = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"installation" ofType:@"plist"]];
      NSDictionary *app_config = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle bundleWithPath:@"/path/to"] pathForResource:@"something/data" ofType:@"plist"]];
      [_configuration addEntriesFromDictionary: core_config];
      [_configuration addEntriesFromDictionary: app_config];
      NSLog(@"merged: %lu, core: %lu, app: %lu", (unsigned long)[_configuration count],  (unsigned long)[core_config count],  (unsigned long)[app_config count]);
      // merged: 0, core: 4, app: 5
    }
    return _configuration;
    }

_configuration为空,尽管两次调用addEntriesFromDictionary

2 个答案:

答案 0 :(得分:2)

在向其添加条目之前是否已初始化NSMutableDictionary?

{{1}}

答案 1 :(得分:1)

这有效:

-(NSMutableDictionary*) configuration{
    if (!_configuration) {
        NSDictionary *core_config = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"installation" ofType:@"plist"]];
        NSDictionary *app_config = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle bundleWithPath:@"/Volumes/RolloutSDKInstaller"] pathForResource:@".rollout/app" ofType:@"plist"]];
        _configuration = [NSMutableDictionary dictionaryWithDictionary: core_config];
        [_configuration addEntriesFromDictionary: app_config];
        NSLog(@"merged: %lu, core: %lu, app: %lu", (unsigned long)[_configuration count],  (unsigned long)[core_config count],  (unsigned long)[app_config count]);
        //merged: 9, core: 4, app: 5
    }

    return _configuration;
}