Search code examples
objective-cios7nsmutabledictionary

When I setObject to NSMutableDictionary previous objects added are deleted


This is the code to add objects to a NSMutableDictionary:

-(void)mapUserFields: (UIControl *) sender  {

nsd = [[NSMutableDictionary alloc]init];

int tagValue = sender.tag;
UITextField *field  = [sender viewWithTag: tagValue];

[nsd setObject:field.text forKey:[NSString stringWithFormat:@"%d", tagValue]];

NSLog(@"\nfield.text: %@  tagValue: %d  nsd.count: %d\n",field.text, tagValue, nsd.count);
}

This is the output from the debugger console:

2014-09-17 15:18:10.022 Books[20738:60b] 
field.text: 2  tagValue: 0  nsd.count: 1
2014-09-17 15:18:11.394 Books[20738:60b] 
field.text: 4  tagValue: 1  nsd.count: 1
2014-09-17 15:18:16.918 Books[20738:60b] 
field.text: 6  tagValue: 2  nsd.count: 1
2014-09-17 15:18:18.863 Books[20738:60b] dictionary.count: 1

As you can see, the count remains at 1, but the data is valid. What is wrong, and how do I fix it?


Solution

  • As indicated by Josh above, this line is your problem:

    nsd = [[NSMutableDictionary alloc]init];
    

    because it replaces the entire dictionary with a new one. So it isn't that adding one key is removing another, it's that you're explicitly throwing the earlier data away.

    Perhaps try:

    if (nds == nil) {
        nsd = [[NSMutableDictionary alloc]init];
    }