Please tell me how can we have multiple values for the same key in NSMutableDictionary?
When I use the below approach, the values are being replaced with the recent one.
In my case:
[dictionary setObject:forename forKey:[NSNumber numberWithint:code]];
[dictionary setObject:surname forKey:[NSNumber numberWithint:code]];
[dictionary setObject:reminderDate forKey:[NSNumber numberWithint:code]];
When I view the contents of the dictionary, I get only the reminderDate
for key code. Here, the code is same for all values. How do I avoid forename and surname being replaced by plannedReminder
.
Thank You!
I don't think you understand how dictionaries work. Each key can only have one value. You'll want to have a dictionary of dictionaries or a dictionary of arrays.
Here you create a dictionary for each person, and then store that in your master dictionary.
Modern syntax is much cleaner.
A. If you're building a static structure at load time:
B. If your adding items in real time(probably):
Then you access as a 2D dictionary...
It seems like you are using
code
as the key and you want to represent multiple values based oncode
. In that case, you should either:Abstract all data associated with
code
into a separate class (perhaps calledPerson
) and use instances of this class as values in the dictionary.Use more than one layer of dictionaries:
If you are really adamant about storing objects in a dictionary, and if you are dealing with strings, you could always append all of your strings together separated by commas, and then when you retrieve the object from the key, you'll have all your objects in a quasi-csv format! You can then easily parse that string into an array of objects.
Here is some sample code you could run:
And then to retrieve and parse the object in the dictionary:
It might not be as clean as having layers of dictionaries like dreamlax suggested, but if you are dealing with a dictionary where you want to store an array for a key and the objects in that array have no specific keys themselves, this is a solution!