2011-12-09 74 views
1

我有兩個plist文件,我用它們作爲數據源在我的應用程序中創建NSArrayNSDictionaries我需要將兩個NSArray/NSDictionaries結合在一起

我想要的CSV文件的輸出看起來像:

exerciseName, muscleGroup, description 
Barbell Curl, Biceps, This is a bicep exercise 

的問題是,我需要首先將兩個NSDictionaries我有。一個有exerciseName和muscleName,另一個有exerciseDescription。但我需要爲每個練習對象提供一個包含所有3個鍵的字典數組。

我用下面的代碼來構建主NSMutableArray

if (muscleArray == nil) 
    { 
     NSString *path = [[NSBundle mainBundle]pathForResource:@"data" ofType:@"plist"]; 
     NSMutableArray *rootLevel = [[NSMutableArray alloc]initWithContentsOfFile:path]; 
     self.muscleArray = rootLevel; 
    } 

    NSMutableArray *arrayForSearching = [NSMutableArray array]; 
    for (NSDictionary *muscleDict in self.muscleArray) 
     for (NSDictionary *excerciseDict in [muscleDict objectForKey:@"exercises"]) 
      [arrayForSearching addObject:[NSDictionary dictionaryWithObjectsAndKeys: 
              [excerciseDict objectForKey:@"exerciseName"], @"exerciseName", 
              [muscleDict objectForKey:@"muscleName"], @"muscleName", nil]]; 
    self.exerciseArray = arrayForSearching; 

我用下面的代碼來構建具有exerciseDescription關鍵

NSString *exerciseNameString =self.exerciseName; 
    NSString *path = [[NSBundle mainBundle] pathForResource:@"ExerciseDescriptions" ofType:@"plist"]; 

    NSDictionary *exerciseDescription = [NSDictionary dictionaryWithContentsOfFile:path]; 
    NSString *description = [exerciseDescription objectForKey:exerciseNameString]; 
+0

我不清楚你的問題是什麼。 – ThomasW

回答

1

你明明知道是怎麼的NSDictionary遍歷並創建字典,那麼問題是什麼?

通過exerciseArray進行迭代併爲每個詞典添加練習描述。然而,這看起來非常低效,你應該重新考慮整個事情。爲什麼不將它們以即用格式存儲在磁盤上?

數組的順序很重要時使用數組。這似乎並不重要,所以爲什麼不把它們作爲NSDictionaries?如果您需要訪問字典中的所有密鑰,只需致電allKeys

編輯:像這樣?

NSString *path = [[NSBundle mainBundle] pathForResource:@"ExerciseDescriptions" 
    ofType:@"plist"]; 
NSDictionary *descriptions = [NSDictionary dictionaryWithContentsOfFile:path]; 

NSMutableArray *exercises = self.exerciseArray; 
for (NSInteger i = 0; i < [exercises count]; i++) { 

    NSMutableDictionary *dict = [[exercises objectAtIndex:i] mutableCopy]; 
    NSString *name = [dict valueForKey:@"exerciseName"]; 
    NSString *desc = [descriptions valueForKey:name]; 

    if (desc) { 
     [dict setValue:desc forKey:@"exerciseDescription"]; 
     [exercises replaceObjectAtIndex:i withObject:dict]; 
    } 
    [dict release]; 
} 
0

我創建了以下項目,以解決我需要合併從Plist檔案創建兩個字典: https://github.com/bumboarder6/NSDictionary-merge

它的工作原理,即使你有你的兩本字典或陣列之間存在一些重複的條目,它也是遞歸合併所以即使它包含字典陣列的字典(等等),你也可以將整個plist合併。