在另一个NSDictionary中的NSMutableDictionary中将对象添加到NSMutableArray

时间:2012-06-12 16:12:02

标签: ios nsmutablearray add nsmutabledictionary

所以我在带有数组的字典中有一个字典。我试图添加到第二个字典中的数组。

 [mealInfo setObject:[[NSMutableDictionary alloc]init] forKey:@"breakfast"];
 [[mealInfo objectForKey:@"breakfast"] setObject:[[NSMutableArray alloc] init] forKey:@"name"];
    [[mealInfo objectForKey:@"breakfast"] setObject:[[NSMutableArray alloc] init] forKey:@"detail"];
    [[mealInfo objectForKey:@"breakfast"] setObject:[[NSMutableArray alloc] init] forKey:@"ndb"];
    [[mealInfo objectForKey:@"breakfast"] setObject:[[NSMutableArray alloc] init] forKey:@"id"];
    [[mealInfo objectForKey:@"breakfast"] setObject:[[NSMutableArray alloc] init] forKey:@"alias"];

创建似乎只是在向数组添加多个元素时,我最终会遇到SIGABRT错误

我像这样添加

[[[initMealInfo->mealInfo objectForKey:@"breakfast"] objectForKey:@"name"] addObject:[food_prop objectForKey:@"description"]];

我知道我做错了什么,想知道什么帮助会受到高度赞赏。

1 个答案:

答案 0 :(得分:3)

首先,你使用ARC吗?否则你会遇到很多麻烦。


您应该阅读最少知识原则和Law Of Demeter

让这样的结构更直观:

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

    NSMutableDictionary *breakfast = [[NSMutableDictionary alloc] init];
    [breakfast setObject:[[NSMutableArray alloc] init] forKey:@"name"];
    [breakfast setObject:[[NSMutableArray alloc] init] forKey:@"detail"];
    [breakfast setObject:[[NSMutableArray alloc] init] forKey:@"ndb"];
    [breakfast setObject:[[NSMutableArray alloc] init] forKey:@"id"];
    [breakfast setObject:[[NSMutableArray alloc] init] forKey:@"alias"];

    [mealInfo setObject:breakfast forKey:@"breakfast"];

然后尝试输入信息并将其包装在函数

中时尝试将其分解
-(void) addMealName:(NSString*) name forMeal:(NSString*) meal 
{
    NSMutableDictionary *meals = [mealInfo objectForKey:meal];
    NSMutableArray *mealNames = [breakfast objectForKey:@"name"];
    [mealNames addObject:name];
    [meals setObject:breakfastNames forKey:@"name"];
    [mealInfo breakfast forKey:meal];
}

并致电

NSString *newMealName = [food_prop objectForKey:@"description"];
[initMealInfo addMealName:newMealName forMeal:@"breakfast"];