2015-06-24 112 views
2

我試圖合併2 NSDictionary對象到1 NSMutableDictionary。通過閱讀2個不同的plist文件創建了NSDictionary。 ,如何結合兩個NSDictionaries?

@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兩次。

+0

什麼是你的問題?你有什麼問題? – rmaddy

回答

2

在添加條目之前是否已初始化您的NSMutableDictionary?

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

是啊!剛剛意識到它沒有被初始化。謝謝! – agoldis

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