Rob
Rob

Reputation: 426

Adding object to NSMutableArray in an NSMutableDictionary in another NSDictionary

So I have a dictionary in a dictionary with arrays. I am trying to add to the arrays that are in the second dictionary.

 [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"];

The creation seems to be working just the adding multiple elements to the arrays is where I end up with a SIGABRT error

I add like such

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

I know I am doing something wrong and would like to figure out what any help would be greatly appreciated.

Upvotes: 0

Views: 5297

Answers (1)

James Webster
James Webster

Reputation: 32066

Firstly, are you using ARC? Else you have a lot of trouble.


You should read up on the Principle of Least Knowledge and the Law Of Demeter

Is making the structure like this more intuitive:

    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"];

Then try breaking it down a bit when you try to enter information and wrap it in a function

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

And call

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

Upvotes: 3

Related Questions