agoldis
agoldis

Reputation: 1067

How to combine two NSDictionaries?

I'm trying to merge 2 NSDictionary objects into 1 NSMutableDictionary. NSDictionarys are created by reading 2 distinct plist files.

    @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;
    }

The _configuration is empty, despite calling addEntriesFromDictionary twice.

Upvotes: 2

Views: 4154

Answers (2)

agoldis
agoldis

Reputation: 1067

This worked:

-(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;
}

Upvotes: 1

paolo
paolo

Reputation: 111

Did you init your NSMutableDictionary before adding entries to it?

NSMutableDictionary *configuration = [[NSMutableDictionary alloc] init];

Upvotes: 2

Related Questions