iGatiTech
iGatiTech

Reputation: 2268

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.

Upvotes: 0

Views: 403

Answers (2)

William Hu
William Hu

Reputation: 16149

Try this:

@property(nonatomic, copy) NSMutableDictionary *dictMain;
@property(nonatomic, copy) NSMutableDictionary *dictSubMain;

Actually actually whenever you use NSMutable* style use copy keyword, that's why it exists.

Or change:

dictSubMain = [[NSMutableDictionary alloc] initWithDictionary:dictMain];

to:

dictSubMain = [[NSMutableDictionary alloc] initWithDictionary:dictMain copyItems:YES];

Upvotes: 0

Avi
Avi

Reputation: 7552

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.

Upvotes: 1

Related Questions