我有两个plist
个文件,我用它作为数据源在我的应用中创建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键
的NSDictionary NSString *exerciseNameString =self.exerciseName;
NSString *path = [[NSBundle mainBundle] pathForResource:@"ExerciseDescriptions" ofType:@"plist"];
NSDictionary *exerciseDescription = [NSDictionary dictionaryWithContentsOfFile:path];
NSString *description = [exerciseDescription objectForKey:exerciseNameString];
答案 0 :(得分:0)
你显然知道如何迭代并创建字典,那么问题是什么?
遍历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];
}
答案 1 :(得分:0)
我创建了以下项目来解决我需要合并从plist创建的两个词典: https://github.com/bumboarder6/NSDictionary-merge
即使你的两个词典或数组之间有一些重复的条目,它也可以工作,它也会递归合并,所以即使它包含字典数组字典的字典(等),你也可以合并整个plist。