Search code examples
iosobjective-cnsmutablearraynsmutabledictionary

Array of dictionary value changes is reflect in all the values


I have NSMutableArray and Added NSMutableDictionary

If i update one value for specific row then all the values changes in NSMutableDictionary.

NSIndexPath *qtyIndex

-(void)demoDefaultCartValues{

    [dict_CartItems setValue:@"Item 1 KK Demo" forKey:@"DIC_PRODUCT_NAME"];
    [dict_CartItems setValue:@" KK Demo" forKey:@"SELLER_NAME"];
    [dict_CartItems setValue:@"1" forKey:@"QTY_VALUE"];
    [dict_CartItems setValue:@"42" forKey:@"SIZE_VALUE"];
    [dict_CartItems setValue:@"1250" forKey:@"PRICE_VALUE"];
    [dict_CartItems setValue:@"1500" forKey:@"DISCOUNT_VALUE"];

    for (int i = 0; i <= 5; i++) {
        [cartListArray addObject:dict_CartItems];
    }

}

#pragma mark - DropDown Delegate

    -(void)dropDownView:(UIView *)ddView AtIndex:(NSInteger)selectedIndex{

        [[cartListArray objectAtIndex:qtyIndexPath.row] setValue:[sizeArrayList objectAtIndex:selectedIndex] forKey:@"QTY_VALUE"];

        NSLog(@"What %@",cartListArray);
    }

If I update qty 1 to 5 then all dictionary values QTY_Value changes to 5.


Solution

  • Use new Objective-C features (more than 5 years old) to make this more readable. And add six different mutable dictionaries to the array:

    NSDictionary* dict = { @"DIC_PRODUCT_NAME":@"Item 1 KK Demo",
                           @"SELLER_NAME":@" KK Demo",
                           @"QTY_VALUE": @"1",
                           etc.
                          };
    
    for (NSInteger i = 0; i < 6; ++i)
        [cartListArray addObject: [dict mutableCopy]];
    

    and later:

    -(void)dropDownView:(UIView *)ddView atIndex:(NSInteger)selectedIndex{
    
        cartListArray [qtyIndexPath.row] [@"QTY_VALUE] = sizeArrayList [selectedIndex];
    }
    

    cartListArray should be declared as

    NSMutableArray <NSMutableDictionary*> *cartListArray;
    

    Now what I would really recommend that you don't store a dictionary at all, but declare a model class. So you don't have to use strings for quantity etc. but NSInteger. Also that cartListArray isn't mutable if you don't want to modify it after it has been initialised. Keep things immutable whenever you can.