字典值变化的数组反映在所有值中

Array of dictionary value changes is reflect in all the values

我有 NSMutableArray 并添加了 NSMutableDictionary

如果我为特定行更新一个值,那么 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);
    }

如果我将数量 1 更新为 5,则所有字典值 QTY_Value 都会更改为 5。

问题是你的代码使用同一个字典,它是一个参考值,所以它是同一个字典的浅拷贝,你可以在每次迭代时创建一个新字典

 -(void)demoDefaultCartValues{


     for (int i = 0; i <= 5; i++) {

      NSMutableDictionary*dict_CartItems = [ NSMutableDictionary new];
      [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"];

       [cartListArray addObject:dict_CartItems];
     }

  }

或者您可以使用 copy / mutableCopy

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

这很明显

当您将 NSMutableDictionary 添加到数组时,数组中包含该字典的引用。

现在你正在做的是在数组中多次插入相同的字典。所以当你改变数组中的单个对象时。所有的地方都受到影响。保留相同的 Dictionary 对象总是会导致此问题。

此问题的解决方案是在每次插入数组之前创建一个新对象。

希望对您有所帮助

使用新的 Objective-C 功能(已有 5 年以上)使其更具可读性。并向数组添加六个不同的可变字典:

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]];

及以后:

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

    cartListArray [qtyIndexPath.row] [@"QTY_VALUE] = sizeArrayList [selectedIndex];
}

cartListArray 应声明为

NSMutableArray <NSMutableDictionary*> *cartListArray;

现在我真的建议您根本不要存储字典,而是声明一个模型class。所以你不必使用字符串来表示数量等,而是使用 NSInteger。如果您不想在初始化后修改它,那么 cartListArray 也是不可变的。尽可能保持事物不变。