views:

44

answers:

2

Hello,

Please tel me how to have many values for the same key in NSMutableDictionary? because when i use the below approach , the values are being replaces 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 dictionary, i get only the reminderDate for key code. here code is same for all values. help me how to avoid forename and surname being replace by plannedReminder.

Thank You

+1  A: 

It seems like you are using code as the key and you want to represent multiple values based on code. In that case, you should either:

  1. Abstract all data associated with code into a separate class (perhaps called Person) and use instances of this class as values in the dictionary.

  2. Use more than one layer of dictionaries:

    NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
    
    
    NSMutableDictionary *firstOne = [NSMutableDictionary dictionary];
    [firstOne setObject:forename forKey:@"forename"];
    [firstOne setObject:surname forKey:@"surname"];
    [firstOne setObject:reminderDate forKey:@"reminderDate"];
    
    
    [dictionary setObject:firstOne forKey:[NSNumber numberWithInt:code]];
    
    
    // repeat for each entry.
    
dreamlax
+1  A: 

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.

NSDictionary *d = [NSDictionary dictionaryWithObjectsAndKeys:
forename, @"forename", surname, @"surname", @reminderDate, "@reminderDate", nil];

[dictionary setObject:d forKey:[NSNumber numberWithint:code]];
Paul Schreiber