Gati Gati - 4 months ago 28
Objective-C Question

NSMutableDictionary assignment

Facing issue with

NSMutableDictionary
,

I have one main mutable dictionary, which is
dictMain
,

Taken another mutable dictionary, which is
dictSubMain
,

Declaration as below in ViewController.m file,

@interface ViewController ()
{
NSMutableDictionary *dictMain;
NSMutableDictionary *dictSubMain;
}


Now I have some values filled in
dictMain
initially from viewDidLoad method.

I have one another method, in which very firstly I am assigning
dictMain
to another mutable dictionary
dictSubMain
then I made some changes in
dictSubMain
but the issue is whatever changes I am making in
dictSubMain
that same changes reflecting on
dictMain
also. I don't want to make any changes in
dictMain
.

Below is my code,

-(void)addRowsInTable:(NSInteger)index
{
dictSubMain = [[NSMutableDictionary alloc] initWithDictionary:dictMain];

NSMutableArray *tmpArray = [[NSMutableArray alloc] init];
NSMutableDictionary *tmpDic = [[NSMutableDictionary alloc] init];

[tmpDic setObject:self.btnTTNumDent.currentTitle forKey:kNUMDENT_T];
[tmpDic setObject:self.btnTTSizeDent.currentTitle forKey:kSIZEDENT_T];
[tmpArray addObject:tmpDic];
[[[dictSubMain valueForKey:kDATA] objectAtIndex:index] setObject:tmpArray forKey:kTABLE];
}


Can anyone help me out to resolve it! Thanks in advance.

Avi Avi
Answer

It looks like dictSubMain[kDATA] is an array of mutable dictionaries. You are probably having a problem because [[NSMutableDictionary alloc] initWithDictionary:dictMain] creates a shallow copy of dictMain, so dictSubMain contains the same instance of the array at kDATA as dictMain.

You need to perform a deep copy instead. Methods for doing so are easily searched for. I am sure there are many answers available on SO.