user3547147
user3547147

Reputation: 51

Can Only add one object to NSMutableDictionary

I have a datepicker and a UIBarButtonItem, when the UIBarButtonItem is pressed it invokes a method to add the selected date to an NSMutableDictionary. The code is shown below:

diaryDateArr = [[NSArray alloc] initWithObjects:diaryDate, nil];
NSString *dateKeyStr = [NSString stringWithFormat:@"dateKey%d", dicDates.count+1];
diaryKeyStrArr = [[NSArray alloc] initWithObjects:dateKeyStr, nil];
dicDates = [[NSMutableDictionary alloc] initWithObjects:diaryDateArr forKeys:diaryKeyStrArr];
NSArray * allKeys = [dicDates allKeys];
for(NSString *key in [dicDates allKeys]) { NSLog(@"%@",[dicDates objectForKey:key]);}
NSLog(@"Count : %d", [allKeys count]);

However, it all seemingly works until I count how many keys are within the NSMutableDictionary and count is returned as 1, even if i click the button twice of two different dates which should theoretically (or at least how i would like to) should add another date which is selected in the date picker making the count 2. but it never changes from 1

How are the objects and keys not being placed into the dictionary?

Regards

Upvotes: 0

Views: 134

Answers (1)

Ethan Mick
Ethan Mick

Reputation: 9567

Count is returning the number of entries in the dictionary - One. You can access it by doing: [dicDates valueForKey:diaryKeyStrArr];

If you click the button a second time, your dictionary is being set to a new one. Try this perhaps:

if (!dicDates) {
    dicDates = [[NSMutableDictionary alloc] initWithObjects:diaryDateArr forKeys:diaryKeyStrArr];
} else {
    dicDates[dateKeyStr] = diaryDateArr;
}

Upvotes: 1

Related Questions